PDA

View Full Version : How to maintain session Object?


blust1984
Jun 18th, 2007, 06:09 PM
Hello,
I am developing a web application. in login part, I can pass the username and password to a SimpleFormController, according to the username, I will get a User object from database, but how can I keep this User object as a session Object that all the other controllers in the web application also can get it during the web flow?

For example, after login, the loginController can get the User object, and go to index page, which is mapped to another controller, also want to use this User Object. How to keep this session Object during the session until user logout?

Isaac2001
Jun 18th, 2007, 06:31 PM
I think you are receibing data in your formControler with a method like this:


public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)throws ServletException, Exception {
String user=((BackingObject)command).getUser();
String psw=((BackingObject)command).getPsw();

}

now if you want keeping the username in a session only you have to put it in a session object, now to get this object you need to use the session object which is contained in HttpServletRequest object that is being received in you onSubmit method, something Like this:


public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)throws ServletException, Exception {
String user=((BackingObject)command).getUser();
String psw=((BackingObject)command).getPsw();

//userValid is you validation method
if(userValid(user,psw)){
HttpSession session=request.getSession();
session.setAttribute("user",user);
return new ModelAndView(new RedirectView(this.getSuccessView()));
}

//if user is no valid redirect HIM/HER to an error view
return new ModelAndView("error.view");

}

now your object is in a session, now if you want to displayit for example in another JSP you only need to call it, for example using JSTL or Scriplet


//with JSTL
Hi ${sessionScope['user']} you're welcome;

//using a Scriplet
Hi <% out.println(session.getAttribute("user")); %>you are welcome;

//or binding with backng object
<form:input path="user" />;


Prev line should display the username in your JSP.

Also you can to recover the same values form other Controller. Obtaining the session from request and using getAttribute(" ") method.