views:

253

answers:

2

I know that I can use the getParameter() to pass client-side objects, but I am wondering what to use to pass server-side objects like I do with the getParameter. I have seen the getAttribute but do I need to use the setAttribute on the first JSP page and then the getAttribute on the second page. Any help would be greatly appriciated.

A: 
  • If you are using forward (jsp:foprward or RequestDispatcher) from one page to another, then use request.setAttribute(..) and request.getAttribute(), because you are within the same request
  • If you are using redirect (via response.sendRedirect()), then use request.getSession().setAttribute(..) and request.getSession().getAttribute()
Bozho
+1  A: 

You normally don't want to literally pass objects from JSP to JSP. You need to put the object in the scope just there which the (other) JSP can access. You also normally don't want to write raw Java code inside JSP files to achieve that. Use a real Java class for this in combination with plain vanilla Expression Language.

Here's an (semi-pseudo)example of storing information in the request scope which JSP in turn can access using EL. First the servlet:

protected void doGet(request, response) {
    request.setAttribute("message", "Blah yadda blah.");
    request.getRequestDispatcher("page.jsp").forward(request.response);
}

Now the JSP:

<p>Message was: ${message}</p>

If you invoke this servlet by e.g. http://example.com/context/servlet, then you will see the message to show up in the output.

If you want to keep the information a bit longer around, such as the logged-in User, then you can use the session scope for this:

protected void doPost(request, response) {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    User user = userDAO.find(username, password);
    if (user != null) {
        request.getSession().setAttribute("user", user);
        response.sendRedirect("home");
    } else {
        request.setAttribute("message", "Unknown user, please try again.");
        request.getRequestDispatcher("login.jsp").forward(request.response);
    }
}

The User object is now accessible across all requests inside the same session until you explicitly remove it from session (logout) or until the session get invalidated (timed out). The JSP example which you can use in any JSP page requested in the same session:

<p>You're logged in as ${user.name}</p>

Alternatively/additionally, you can use the JSTL's <c:set> tag to set an attribute/object in a certain scope inside a JSP file. But you often don't need this for this particular purpose ("passing objects to another page").

BalusC