8

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
palAlaa
  • 9,500
  • 33
  • 107
  • 166

4 Answers4

11

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
9

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

YoK
  • 14,329
  • 4
  • 49
  • 67
0

Sure you can, simply include it in your action in the form. But you have to write the correct doPost or doGet to handle the request!

Truong Ha
  • 10,468
  • 11
  • 40
  • 45
0

If you want to call a particular servlet method than you also use Expression Language. For example, you can do something like:

Servlet

ForexTest forexObject = new ForexTest();
request.setAttribute("forex", forexObject);

JSP

<body bgcolor="#D2E9FF">
Current date : ${forex.rate}
</body>
Rachel
  • 100,387
  • 116
  • 269
  • 365
  • Note, your answer is a bit misleading, it is implying that `ForexTest` needs to be a servlet, but it doesn't necessarily need to be a servlet at all. The normal approach is that it's a Javabean and that those `get` methods should **only** be called to access properties, not to execute business logic. – BalusC Oct 14 '10 at 11:15