Vitalii
Vitalii

Reputation: 11071

How can I set a session variable in a servlet and get it in a JSP?

I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page

@WebServlet("/Welcome")
public class WelcomeServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException
    {
        HttpSession session = request.getSession();
        session.setAttribute("MyAttribute", "test value");

        // response.sendRedirect("index.jsp");
        RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
    }

}

And simple jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>My Index page</title>
</head>
<body>
Index page
<br />
 <% 
Object sss = request.getAttribute("MyAttribute"); 
String a = "22";

%>

   <%= request.getAttribute("MyAttribute"); %>
</body>
</html>

Whatever I do attribete at jsp is null.

What is wrong at this simple code?

Upvotes: 2

Views: 88858

Answers (3)

Braj
Braj

Reputation: 46841

you are getting if from request not session.

It should be

session.getAttribute("MyAttribute")

I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.

${sessionScope.MyAttribute}

or

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

<c:out value="${sessionScope.MyAttribute}" />

you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.

Read more

Upvotes: 9

Ioan
Ioan

Reputation: 5187

You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.

Simply replace :

<% 
Object sss = request.getAttribute("MyAttribute"); 
String a = "22";

%>

with simply using EL ${MyAttribute}

But if you want to stick with scriptlets, you should get the attribute from the proper scope which is session in your case.

Upvotes: 3

helderdarocha
helderdarocha

Reputation: 23637

You set an attribute in a session. You have to retrieve it from a session:

Object sss = session.getAttribute("MyAttribute");

And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:

request.setAttribute("MyAttribute", "test value");

Then read it as you are already doing in you JSP.

Upvotes: 4

Related Questions