Harshit
Harshit

Reputation: 5157

Sessions in Spring MVC

I would like to know how sessions gets used in spring mvc to retain the value until the user logged in.

Somewhere I found model.addAttribute("session_name",username); for creating the session & access as ${username} in the jsp page. Is it the real way web can define & access username variable in all the pages?

How can I check if the session with variable name username exists? In JSP I used to use

if(null == session.getAttribute("username")){  
  // User is not logged in.  
}else{  
  // User IS logged in.  
} 

How can I check in spring mvc ?

Upvotes: 0

Views: 173

Answers (1)

Gajendra Kumar
Gajendra Kumar

Reputation: 918

session is already created by spring container when you need it just put in arguments of your controllers method and it will be injected. User Login Example

@RequestMapping(value=("login"),method=RequestMethod.POST)
public String login(@RequestParam("name")String name,@RequestParam("pass")String pass,@RequestParam("gName")String gName,HttpSession session
        ) {

    User u1=new User();
    u1.setName(name);
    u1.setgName(gName);
    u1.setPass(pass);
    User u2=dao.findById(name);
    if(u2!=null)
    { if(u1.getPass().equals(u2.getPass())&&u1.getgName().equals(u2.getgName()))
        {

            session.setAttribute("user", u1);
            return "welcome";
        }
        else
        {
            return "error";
        }
    }
    else
    {
        return "error";
    }


}

Now you can get it in any jsp page following way:

if(session.getAttribute("user")!=null)
{
    User user=(User)session.getAttribute("user");

}
else 
{
   out.print("Log in please");

 }

Upvotes: 1

Related Questions