When a servlet is called, a page is loaded from a JSP file
P粉289775043
2023-08-24 12:47:14
<p>Can I call a servlet from a JSP file without using an HTML form? </p>
<p>For example, display results from a database in an HTML table during page load. </p>
You need to use the forward/include method of RequestDispatcher according to your needs to achieve the same effect.
In JSP you need to use the following tags:
jsp:include:
For example:
jsp:forward:
For example:
Please see Advanced JSP Example: JSP-Servlet Communication:
http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html
You can use the servlet's
doGet()
method to preprocess the request and forward the request to the JSP. Then just point to the servlet URL instead of the JSP URL in the link and browser address bar.For example:
Please note that the JSP file is placed in the
/WEB-INF
folder to prevent users from accessing it directly without calling the servlet.Also note that
@WebServlet
only works with Servlet 3.0 (Tomcat 7, etc.), see @WebServlet Notes with Tomcat 7. If you cannot upgrade, or for some reason need to useweb.xml
which is not compatible with Servlet 3.0, you will need to manually register the servlet inweb.xml
as follows instead Usage comments:Once the servlet is properly registered via annotations or XML, you can now open it via http://localhost:8080/context/products, where
/context
is the context path for the web application deployment,/products
is the URL pattern of the servlet. If you have any HTML<form>
in it, then just POST it to the current URL like<form method="post">
and in the same Add adoPost()
to the servlet to perform post-processing work. Please continue reading the following links for more specific examples of this.See also