get value from a session Object

834 views Asked by At

I have a User bean class with constructor and getter and setter

public class User {

    private String username;
    private String password;
}

i have a controller which logs in a user

@PostMapping("/login")
    public String login(@ModelAttribute User user,Model model){
        model.addAttribute("session", user);
        return "index1";
    }   

Also one demo mapping for the same index1 page to check session

@GetMapping("/find")
public String find(Model model){
    return "index1";
}

in the jsp page i am not able to check the user that is populated in the session object

<%@ page errorPage="index.jsp" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
<title>Login Page</title>

</head>
<body>

    <h1>Login</h1>
    <c:if test='${sessionScope.session.user} == "user"'>
        <% session.invalidate(); %>
    </c:if>
    <p>Hello ${sessionScope.session.password}</p>

</body>
</html>

i am using @sessionattribute of Spring to use the session values and my session object name is session .

How to invalidate the session when user is user it always comes as null please help .

How to get the values inside the object that is stored in a session

this is a demo to test session handling

1

There are 1 answers

3
ScanQR On

Following will not work for you,

@PostMapping("/login")
    public String login(@ModelAttribute User user,Model model){
        model.addAttribute("session", user);
        return "index1";
    } 

Because first of all you are not setting anything in the ModelAndView but into a model object which will be nullified once you move to index1 view.

You need to set the if as follows,

   @PostMapping("/login")
    public ModelAndView login(@ModelAttribute User user, Model model, HttpServletRequest request){
         ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("session", user);
    modelAndView.setViewName("index1");
    return modelAndView;
    }