How to call servlet on jsp page load

72,410

Solution 1

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.

Solution 2

(...) but I don't want to display the name of servlet in url.

You don't need to use the Servlet name at all when accessing to a Servlet. In fact, you can create your servlet to point to the desired URL by defining the right URL pattern:

@WebServlet("/index.jsp")
public class LatestProductServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        List<Product> productList = ...
        //all the necessary code to obtain the list of products
        //store it as request attribute
        request.setAttribute("productList", productLlist);
        //forward to the desired view
        //this is the real JSP that has the content to display to user
        request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
    }
}

Then, you will have a folder structure like this

- <root folder>
  - WEB-INF
    + index.jsp
    + web.xml

And in WEB-INF/index.jsp:

<!DOCTYPE html>
<html lang="es">
    <body>
        <!--
            Display the data accordingly.
            Basic quick start example
        -->
        <c:forEach items="${productList}" var="product">
            ${product.name} <br />
        </c:forEach>
    </body>
</html>

Note that your clients will access to http://<yourWebServer>:<port>/<yourApplication>/index.jsp and will get the desired content. And you don't need to fire two GET requests to retrieve the content for your specific page.

Note that you can go further with this approach: Since the pattern is now defined in servlet, you may choose to not use index.jsp for your clients, but index.html to access to your page. Just change the URL pattern in the Servlet:

@WebServlet("/index.html")
public class LatestProductServlet extends HttpServlet {
     //implementation...
}

And the clients will access to http://<yourWebServer>:<port>/<yourApplication>/index.html, which will show the results in WEB-INF/index.jsp. Now both your clients and you will be happy: clients will get their data and you won't show that ugly servlet name in your URL.


Additional

If you have index.jsp as your welcome page in web.xml, this approach won't work because application servlet expects that a real file index.jsp exists. To solve this issue, just create an empty file named index.jsp:

- <root folder>
  - index.jsp  <-- fake empty file to trick the application server
  - WEB-INF
    + index.jsp
    + web.xml

And when accessing to http://<yourWebServer>:<port>/<yourApplication>/, will work as shown above.

Share:
72,410
user3660263
Author by

user3660263

Updated on December 21, 2020

Comments

  • user3660263
    user3660263 over 3 years

    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.

  • Braj
    Braj almost 10 years
    what is the difference between <c:import url="/ProductList" /> and <jsp:include page="/latest_products" />?
  • Erran Morad
    Erran Morad almost 10 years
    @Braj - I don't see any difference. But, one forum they said its better to use EL instead of old jsp tags and scripting. I dunno why.
  • Braj
    Braj almost 10 years
    Because JSTL is easy to use and less error prone. Sometime it's very difficult to find out the opening and closing braces in the code. Read more about JavaServer Pages Standard Tag Library
  • Luiggi Mendoza
    Luiggi Mendoza almost 10 years
    @Braj this is not a contest to see who knows more Java web development or not.
  • Braj
    Braj almost 10 years
    @LuiggiMendoza Sorry I apologize for this.
  • Erran Morad
    Erran Morad almost 10 years
    @LuiggiMendoza - dear luiggi, why you say that ?
  • Luiggi Mendoza
    Luiggi Mendoza almost 10 years
    Because the way the question was posted looks like Why are you doing this? while waiting for your answer to later prove that you were wrong and post a wonderful comment revealing the answer. If you have/need to tell something to help to the current knowledge shown, then just say it, don't play with people like that.
  • Luiggi Mendoza
    Luiggi Mendoza almost 10 years
    I show how to do this without using servlet name in URL.
  • Braj
    Braj almost 10 years
    @LuiggiMendoza Now I got your point thanks.
  • Braj
    Braj almost 10 years
    @LuiggiMendoza by the way where is the problem in using serlvet name. We can define it as <url-pattern>/latest_products.jsp</url-pattern> that will look like hitting a jsp page.
  • Luiggi Mendoza
    Luiggi Mendoza almost 10 years
    Yes, and I was expecting that from your edit. But you didn't. Instead, you keep with the 2 GET request approach, which I still see as a bad approach.
  • Braj
    Braj almost 10 years
    @LuiggiMendoza I have suggested it in my last statement. I have never thought in this way. +1 for your answer. I like it.
  • Luiggi Mendoza
    Luiggi Mendoza almost 10 years
    By the way, since my opinion about how to solve this with a single GET request was too large to fit in a comment, I turned it into an answer.