0

I think there should a way to set session variable with defined scope in pure java Servlet without using other library like jsf or springframework so that visibility of session variable can be restricted.

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    String userId = (String)request.getAttribute("userId");
    session.setAttribute("userId", userId);
}

I found ServletContext

ServletContext context = request.getSession().getServletContext();
context.setAttribute("userId", userId);

but this one doesnot seem to provide session scope flexibility.

2
  • What do you mean "restricted", and why put it in the Session in the first place? Commented May 17, 2014 at 4:10
  • I am actually developing liferay portlets and i am also using delegate servlet which is HttpServlet. There is function to limit scope of session variable in PortletSession but i don't find such methods to limit session variable in HttpSession.I am curious. Commented May 17, 2014 at 4:16

1 Answer 1

1

You've found it. Set a session attribute. The scope of a session attribute is the scope of a session, which is a single user.

The portlet scope just controls whether the attribute is confined to the current portlet or is visible to all portlets. It's still within the user session. If you need to implement that feature, just bind a Map into the session under the name of the portlet, and have each portlet look in its own Map.

If you set a context attribute it will be visible to all users.

Sign up to request clarification or add additional context in comments.

6 Comments

can you provide some examples or links. I would like to understand how session scope works.
It's irrelevant how it works. It belongs to a specific user. That's all you need to know. It's guaranteed by the Servlet Specification #7.
currently i am not able to uniformly share session variable from servlet.Some session variables simply just persist in hook and other portlets. Some session variable requires use of LIFERAY_SHARED_ prefix to share with some portlets.
What exactly does 'unable' mean?
i don't understand bind a map into the session under the name of the portlet request.getSession().setAttribute("nameofPortlet",someMap);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.