Calling a Servlet from JSP File on Page Load
Question:
Can a servlet be invoked from a JSP file without employing an HTML form?
Answer:
Absolutely. To accomplish this, utilize the servlet's doGet() method to preprocess the request and subsequently forward it to the JSP. This can be achieved without specifying the JSP URL in the browser's address bar or links. Instead, point the servlet URL.
Example:
Consider the following code snippet:
Servlet (ProductsServlet.java):
@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); } }
JSP (products.jsp):
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> ... <table border="1"> <c:forEach items="${products}" var="product"> <tr> <td>${product.name}</td> <td>${product.description}</td> <td>${product.price}</td> </tr> </c:forEach> </table>
In this example, the doGet() method of the ProductsServlet retrieves a list of products and sets it as a request attribute. The request is then forwarded to the products.jsp page, which iterates over the list and displays the products in a table.
Note:
Ensure that the JSP file is placed within the /WEB-INF folder to prevent unauthorized direct access. Servlet 3.0 (or later) supports the @WebServlet annotation for servlet registration; however, if you are unable to upgrade or need to use web.xml for compatibility reasons, register the servlet manually in web.xml.
Additional Resources:
The above is the detailed content of Can I Call a Servlet from a JSP on Page Load Without Using an HTML Form?. For more information, please follow other related articles on the PHP Chinese website!