Home > front end >  JSP session.getAttribute() returning NULL value
JSP session.getAttribute() returning NULL value

Time:11-05

I have create two JSP page one opens in IE and another opens in EDGE within same application.

How can i share data from One JSP page to another i have tried below but when i try to getAttribute() it return null.

JSP A:

<% HttpSession sess = request.getSession(true); 
        sess.setAttribute("firstName", 100); %>

JSP B:

var firstName = <%=session.getAttribute("firstName")%>

CodePudding user response:

In JEE, there is a notion of scope that can help to store data for different purposes. There 3 scopes :

  • Page scope: the data stored in the page request are only accessible by the page objects.
  • Request scope: the data stored in the request scope are stored in an HttpRequest and are flushed once the request is handled. Other requests can not access what is stored in a request scope.
  • Session scope: the session scope stores data that can be shared by all requests of that session, in this case, it is shared between all requests in the session.
  • Application scope: there is one application scope per Servlet Context and data stored in the application can be accessed by all the sessions, requests, and pages related to that Servlet context.

You can find more information about scopes here.

To answer your question, you should use the application scope to share data between two web browsers.

CodePudding user response:

The session is an implicit object in JSP and can be used directly. You can read about implicit objects in JSP in the Java Tutorial.

<% session.setAttribute("firstName", "100"); %>

You should not create a new session with this code

HttpSession sess = request.getSession(true); 
  • Related