P粉1327308392023-08-25 12:25:47
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:
For example:
<jsp:include page="/HandlerServlet" flush="true">
For example:
<jsp:forward page="/servlet/ServletCallingJsp" />
Please see Advanced JSP Example: JSP-Servlet Communication:
http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html
P粉4222270232023-08-25 10:10:11
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:
@WebServlet("/products") public class ProductsServlet extends HttpServlet { @EJB private ProductService productService; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Product> products = productService.list(); request.setAttribute("products", products); request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); } }
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
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 use web.xml
which is not compatible with Servlet 3.0, you will need to manually register the servlet in web.xml
as follows instead Usage comments:
<servlet> <servlet-name>productsServlet</servlet-name> <servlet-class>com.example.ProductsServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>productsServlet</servlet-name> <url-pattern>/products</url-pattern> </servlet-mapping>
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 a doPost()
to the servlet to perform post-processing work. Please continue reading the following links for more specific examples of this.