简体   繁体   中英

Spring -MVC use session attribute in controller

I have a method where I require the argument name and I have it set as a session attribute as it will be fixed through out the session. However, I have trouble adding it to the function. Any help is appreciated.

LoginController class that sets the session attribute

@Controller
@SessionAttributes({"name", "date"})
public class LoginController {

@Autowired
LoginService service;


/*
 *  Map /login to this method 
 *  localhost:8080/spring-mvc/login
 *  spring-mvc -> dispatcher (todo-servlet.xml)
 *  dispatcher detects login url
 *  dispatcher use view resolver to find .jsp file based on String. In this case, login
 *  view resolver locates login.jsp and shows the content to user via http
 */
@RequestMapping(value = "/test")
// Mark this method as an actual repsonse back to user
@ResponseBody
public String test() {
    return "Hello, world!";
}

@RequestMapping(value ="/")
public String returnLogin() {
    return "redirect:/loginPage";
}

// Only handles get request from the login page
@RequestMapping(value = "/login", method= RequestMethod.GET)
public String loginPage() { 
    // search through the view resolver for login.jsp
    return "login";
}

// Only handles post request from the login page
@RequestMapping(value = "/login", method= RequestMethod.POST)
// @RequestParm to be used for user input
// Model is used to supply attributes to views
// ModelMap has the same functionality has model except it has an addition function where it allows a collection of attributes
public String handleLogin(@RequestParam String name, @RequestParam String password, ModelMap model) {
    if (service.validateUser(name, password)) {
    // Send name to .jsp 
    // use addAttrible( nameAtJSP, nameInRequestParam ) to check for null
    model.addAttribute("name", name);
    model.addAttribute("passWelcome", password);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); 
    String date = sdf.format(new Date());
    model.addAttribute("date", date);
    }
    
    else {
        model.put("errorMessage","Invalid credentials");
        return loginPage();
    }
    return "welcome";   
}

My controller class. I've commented the part that I need to add the session attribute.

@Controller
public class ToDoController {
    
    @Autowired
    private ToDoService service;
    
    @RequestMapping(value = "/list-todo", method= RequestMethod.GET)
    public String showToDo(ModelMap model, String name, String date) {
        model.addAttribute("toDos", service.retrieveTodos("in28Minutes"));
        model.addAttribute("name", name);
        model.addAttribute("date", date);
        // Only returns to the jsp
        return "list-todos";
    }
    
    
    @RequestMapping(value = "/add-todo", method= RequestMethod.GET)
    public String addToDo() {
        return "addToDo";
    }
    
    
    @RequestMapping(value = "/add-todo", method= RequestMethod.POST)
    public String addToDo(ModelMap model,@RequestParam String description) {
        // SESSION ATTRIBUTE NAME
        model.addAttribute("name");
        service.addTodo((String) model.get("name"), description, new Date(), false);
        model.clear();
        return "redirect:/list-todo";
    }

@SessionAttributes doesn't do what you are trying to achieve.

From javadoc of @SessionAttributes :

NOTE: Session attributes as indicated using this annotation correspond to a specific handler's model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session. Therefore, use this facility for such conversational attributes which are supposed to be stored in the session temporarily during the course of a specific handler's conversation.

For permanent session attributes, eg a user authentication object, use the traditional session.setAttribute method instead.

So, what you need to do is:

public String handleLogin(@RequestParam String name, 
                          @RequestParam String password,
                          ModelMap model,
                          HttpSession httpSession) {

    // your code here
    
    httpSession.setAttribute("name", name);

    // your code here
}
    

And then you can retrieve this session attribute in your ToDoController as httpSession.getAttribute("name");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM