4

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()?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Manish Bansal
  • 819
  • 2
  • 8
  • 19

3 Answers3

6

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");
    }
}
pczeus
  • 7,709
  • 4
  • 36
  • 51
1

If you use Spring Security, registered a bean listening for Spring Security's InteractiveAuthenticationSuccessEvent and SessionDestroyedEvent events. These events fire without any explicit configuration in a default Spring Boot environment.

See https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#web.security:

The basic features you get by default in a web application are:

  • . . .
  • A DefaultAuthenticationEventPublisher for publishing authentication events.

By handling these events you can add "username" as a session attribute immediately after a user logons and remove that attribute when the security session (security context) is destroyed:

@Component
public class SessionStoreUsernameAuthEventHandler {

  @EventListener
  public void audit(InteractiveAuthenticationSuccessEvent e) {
    getSession().ifPresent(s -> s.setAttribute("username", e.getAuthentication().getName()));
  }

  @EventListener
  public void audit(SessionDestroyedEvent e) {
    getSession().ifPresent(s -> s.removeAttribute("username"));
  }
  
  private static Optional<HttpServletRequest> getCurrentRequest() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
      .filter(ServletRequestAttributes.class::isInstance)
      .map(ServletRequestAttributes.class::cast)
      .map(ServletRequestAttributes::getRequest);
  }

  private static Optional<HttpSession> getSession() {
    return getCurrentRequest().map(HttpServletRequest::getSession);
  }
}
Brice Roncace
  • 10,110
  • 9
  • 60
  • 69
0
@Autowired
ObjectFactory<HttpSession> httpSessionFactory;
.
.
.
HttpSession session = httpSessionFactory.getObject();

Works good. Thanks to this post.

Mihkel L.
  • 1,543
  • 1
  • 27
  • 42