11

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.

Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47
user3660263
  • 135
  • 1
  • 1
  • 13

3 Answers3

15

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.

Braj
  • 46,415
  • 5
  • 60
  • 76
  • I show how to do this without using servlet name in URL. – Luiggi Mendoza Jun 05 '14 at 20:25
  • @LuiggiMendoza Now I got your point thanks. – Braj Jun 05 '14 at 20:26
  • @LuiggiMendoza by the way where is the problem in using serlvet name. We can define it as `/latest_products.jsp` that will look like hitting a jsp page. – Braj Jun 05 '14 at 20:29
  • 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. – Luiggi Mendoza Jun 05 '14 at 20:30
  • @LuiggiMendoza I have suggested it in my last statement. I have never thought in this way. +1 for your answer. I like it. – Braj Jun 05 '14 at 20:31
6

(...) 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.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

Thanks to +Braj, I am able to make an answer using Expression Language. Apparently, this is supposed to be better than jsp scripting/tags.

Servlet -

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ProductList extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public ProductList() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<String> products = new ArrayList<String>();
        products.add("Car");
        products.add("Gun");
        products.add("Shades");

        request.setAttribute("productsList", products);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}

JSP -

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<c:import url="/ProductList" />

<c:set var="myProducts" value="${requestScope.productsList}" />

<h1>List of products from servlet</h1>
<c:forEach var="product" items= "${myProducts}" varStatus="i">
${product}<br>
</c:forEach>

</body>
</html>
Erran Morad
  • 4,563
  • 10
  • 43
  • 72
  • what is the difference between `` and ``? – Braj Jun 05 '14 at 19:23
  • @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. – Erran Morad Jun 05 '14 at 19:30
  • 1
    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](http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html) – Braj Jun 05 '14 at 19:32
  • @Braj this is not a contest to see who knows more Java web development or not. – Luiggi Mendoza Jun 05 '14 at 19:39
  • @LuiggiMendoza Sorry I apologize for this. – Braj Jun 05 '14 at 19:41
  • @LuiggiMendoza - dear luiggi, why you say that ? – Erran Morad Jun 05 '14 at 20:13
  • 1
    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 Jun 05 '14 at 20:15
  • 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. – Luiggi Mendoza Jun 05 '14 at 20:34