Can I call a servlet from JSP file without using a HTML form?
For example, to show results from database in a HTML table during page load.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use the
doGet()method of the servlet to preprocess a request and forward the request to the JSP. Then just point the servlet URL instead of JSP URL in links and browser address bar.E.g.
Note that the JSP file is placed inside
/WEB-INFfolder to prevent users from accessing it directly without calling the servlet.Also note that
@WebServletis only available since Servlet 3.0 (Tomcat 7, etc), see also @WebServlet annotation with Tomcat 7. If you can’t upgrade, or when you for some reason need to use aweb.xmlwhich is not compatible with Servlet 3.0, then you’d need to manually register the servlet the old fashioned way inweb.xmlas below instead of using the annotation:Once having properly registered the servlet by annotation or XML, now you can open it by http://localhost:8080/context/products where
/contextis the webapp’s deployed context path and/productsis the servlet’s URL pattern. If you happen to have any HTML<form>inside it, then just let it POST to the current URL like so<form method="post">and add adoPost()to the very same servlet to perform the postprocessing job. Continue the below links for more concrete examples on that.See also