How to call servlet on jsp page load

jakarta-ee, java, jsp, servlets

Solution

Solution 1

Steps to follow:

- use `jsp:include` to call the Servlet from the JSP that will include the response of the Servlet in the JSP at runtime

- set the attribute in the request in Servlet and then simply read it in JSP

Sample code:

JSP:

<body>
    <jsp:include page="/latest_products.jsp" />
    <c:out value="${message }"></c:out>
</body>

Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {            
    request.setAttribute("message", "hello");
}

EDIT

but i don't want to display the name of servlet in url.

Simply define a different and meaningful `url-pattern` for the Servlet in the `web.xml` such as as shown below that look like a JSP page but internally it's a Servlet.

web.xml:

<servlet>
    <servlet-name>LatestProductsServlet</servlet-name>
    <servlet-class>com.x.y.LatestProductsServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>LatestProductsServlet</servlet-name>
    <url-pattern>/latest_products.jsp</url-pattern>
</servlet-mapping>

Solution 2

Steps to follow:

- first call to the the Servlet

- process the latest products

- set the list in the request attribute

- forward the request to the JSP where it can be accessed easily in JSP using JSTL

Sample code:

Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {            
    request.setAttribute("message", "hello");
    RequestDispatcher view=request.getRequestDispatcher("index.jsp");
    view.forward(request,response);
}

index.jsp:

<body>      
    <c:out value="${message }"></c:out>
</body>

hit the URL: `scheme://domain:port/latest_products.jsp` that will call the Servlet's `doGet()` method.

Problem

I want to call a servlet `latest_products` on load of `index.jsp` page.This servlet has records in List. I want to pass this `List<products>` to `index.jsp`. But I don't want to display the name of servlet in url. Is there any way by which I can do this.

Original source

Related problems