Calling a servlet from JSP file on page load

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.


Solution 1:

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.

@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>

Note that the JSP file is placed inside /WEB-INF folder to prevent users from accessing it directly without calling the servlet.

Also note that @WebServlet is 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 a web.xml which is not compatible with Servlet 3.0, then you'd need to manually register the servlet the old fashioned way in web.xml as below instead of using the annotation:

<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 having properly registered the servlet by annotation or XML, now you can open it by http://localhost:8080/context/products where /context is the webapp's deployed context path and /products is 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 a doPost() to the very same servlet to perform the postprocessing job. Continue the below links for more concrete examples on that.

See also

  • Our Servlets wiki page
  • doGet and doPost in Servlets
  • How to avoid Java code in JSP
  • Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Solution 2:

You will need to use RequestDispatcher's Methods forward/include depending on your requirement to achieve same.

In JSP you need to use following tags:

jsp:include :

The element allows you to include either a static or dynamic file in a JSP file. The results of including static and dynamic files are quite different. If the file is static, its content is included in the calling JSP file. If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP file.

e.g.

<jsp:include page="/HandlerServlet" flush="true">  

jsp:forward :

The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. The lines in the source JSP file after the element are not processed.

e.g.

<jsp:forward page="/servlet/ServletCallingJsp" />

Check Advanced JSP Sample : JSP-Servlet Communication:

http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html