How to set session attributes in Spring Boot?

Manish Bansal picture Manish Bansal · Mar 17, 2018 · Viewed 11.9k times · Source

I want to set a session attribute with the name that is send by user. User will first login in. And when he logged in I want that his username will set as session attribute.

What should I do?

This is my controller:

@GetMapping("/login")
public String login() {
    return "Login";
}

@PostMapping("/loginCheck")
public String checkLogin(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return "redirect:/"+user.getUsername()+"/";
    } else {
        return "Login";
    }
}

@PostMapping("/signup")
public ModelAndView createuser(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return new ModelAndView("Login");
    } else {
        userService.adduser(user);
        return new ModelAndView("Login");
    }
}


Now how I set the username as session which I am getting in user.getUsername()?

Answer

pczeus picture pczeus · Mar 18, 2018

In SpringMVC you can have the HttpSession injected automatically by adding it as a parameter to your method. So, you login could be something similar to:

@GetMapping("/login")
public String login(@ModelAttribute("users") Users user, HttpSession session)
{
    if(userService.authUser(user)) { //Made this method up
        session.setAttribute("username", user.getUsername());
        view.setViewName("homepage"); //Made up view
    }
    else{
        return new ModelAndView("Login");
    }
}