1

Possible Duplicate:
How to pass an Object from the servlet to the calling JSP

How can I pass object from servlet to JSP?

I have used the following code in the servlet side

request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp");  
if (dispatcher != null){  
dispatcher.forward(request, response);  
}

and this code in JSP side

    <td><%out.println(request.getAttribute("ID"));%> </td>
    <td><%out.println(request.getAttribute("Name"));%> </td>

I get null results in the JSP Page

Community
  • 1
  • 1
user1576197
  • 43
  • 1
  • 1
  • 5

2 Answers2

1

Put it in the session (session.setAttribute("foo", bar);) or in the request; then it is accessible from the JSP through the name you gave it ("foo" in my example).

EDIT : Use simply <%= ID %> and <%= Name %> instead of <%out.println.....%>. Note the = at the beginning of the java tag, indicating to output the result of the expression.

kgautron
  • 7,915
  • 9
  • 39
  • 60
  • You access it the wrong way, I edited my answer. – kgautron Aug 27 '12 at 14:41
  • org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 27 in the jsp file: /MangeNotifications.jsp ID cannot be resolved to a variable 24: 25: 26: 27: <%=ID%> 28: 29: 30:   – user1576197 Aug 27 '12 at 20:51
  • You're confusing `<%= %>` with `${}`. See also http://stackoverflow.com/tags/servlets/info and http://stackoverflow.com/tags/el/info – BalusC Aug 27 '12 at 21:09
1

I think servlet's service (doGet/doPost) method is not requested. In order to access request attributes in JSPs, you must request the servlet via url-pattern and that way you don't have to use session.

SampleServlet.java


@WebServlet(name = "SampleServlet", urlPatterns = {"/sample"})
public class SampleServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
   request.setAttribute("ID", "MyID");
   request.setAttribute("Name", "MyName");
   RequestDispatcher dispatcher = request
                       .getRequestDispatcher("/MangeNotifications.jsp");  
   if (dispatcher != null){  
      dispatcher.forward(request, response);  
   }
  }
}

MangeNotifications.jsp (I presume that this file is located at root of web-context)


<br/>ID : ${ID}     Or scriptlets  <%-- <%=request.getAttribute("ID")%>  --%> 
<br/>ID : ${Name}

Now open the browser and set request url somersetting like this,

http://localhost:8084/your_context/sample
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186