Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set session attribute in java? [duplicate]

Tags:

I am able to set session attribute in scriptlet but when I am trying to set session attribute inside java class it shows error like "session cannot be resolved". So how to set session in java?

<%String username = (String)request.getAttribute("un"); session.setAttribute("UserName", username);%> 
like image 297
sujoy Avatar asked Nov 28 '11 08:11

sujoy


People also ask

How do I create a session attribute?

The client can create session attributes in a request by calling either the PostContent or the PostText operation with the sessionAttributes field set to a value. A Lambda function can create a session attribute in a response.

How do you create a session variable in Java?

One servlet can create session variables and other servlets can fetch or change the value of session variables. Servlet must be a sub class of HttpServlet. Use set attribute method of Httpsession to create session variables. Use getAttribute() of Httpsession to find value of session variables.

How does session setAttribute work?

setAttribute. Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. After this method executes, and if the new object implements HttpSessionBindingListener , the container calls HttpSessionBindingListener.

How can use session setAttribute in Javascript?

var strTest=document. getElementById('DropDownList1'). value; <%Session["Test"] = "'+ strTest +'";%> var session_value='<%=Session["Test"]%>'; alert(session_value);


2 Answers

By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods

public void doGet(HttpServletRequest request, HttpServletResponse response) {      HttpSession session = request.getSession();     String username = (String)request.getAttribute("un");     session.setAttribute("UserName", username); } 
like image 183
oks16 Avatar answered Sep 22 '22 15:09

oks16


By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession() s.setAttribute("name","value"); 

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();    Map m=ctx.getSession();    m.put("name", value); 

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

like image 43
Sheo Avatar answered Sep 20 '22 15:09

Sheo