0

I'm doing a little project with Spring 3 MVC & jQuery

I'm not sure how to ask it so i'll try to explain

I have this scenario :

LoginPage(with User object model) ---submit--> Server sends OK back to LoginPage --> (LoginPage) redirect to Page2 using window.location = "Page2"

Problem : Page 2 doesn't recognize User

How to make it work? I tried reading about @SessionAttributes but didn't really understand it.

@Controller
public class LoginController {
...
...
    @RequestMapping(value = "/")
    public ModelAndView  loginPage(ModelMap model) {
        model.addAttribute("user", new User());
        logger.info("Loading Login Page");
        return new ModelAndView("login");   
    }


      @RequestMapping(value = "/loginSubmit.html" ,method=RequestMethod.GET)
      public String processSubmit( ModelMap model,  User user) throws InterruptedException{
      ...
      ...
      return "1" to login page
      ...
      ...

Here I want User user to be known from last controller,but it's making a new one instead.

@Controller
public class Controller2 {
    @RequestMapping(value = "/home")
    public String home(ModelMap model, User user) {
        ...
        ...
}

LoginPage.jsp

    $.get("loginSubmit.html", form1Var.serialize(), function(data){
      var isSucess = data.charAt(0) == "1" ? true : false;   
      if ( isSucess == true) {
          alert("ok...");
          window.location = "home";
      } 

EDIT Moved my solution to Answers.

Zakos
  • 1,492
  • 2
  • 22
  • 41

2 Answers2

1

By default the server side in Spring MMVC is stateless. To save state between requests you must put the data you want to save in the session. This data is then available for every request in the same session (i.e. from the same client).

In the solution you found, the @SessionAttributes("user") annotation has told Spring MVC to that you want the user object to be persisted across requests by saving it in the session. This is how Spring abstracts you from all the work of actually maintaining the state yourself.

Dónal Boyle
  • 3,049
  • 2
  • 25
  • 40
1

My Solution :

@SessionAttributes("user")

on both controllers

and

@ModelAttribute("user") User user 

as param in the method - worked

I'v also added

@ExceptionHandler(HttpSessionRequiredException.class)
public String SessionException(HttpSessionRequiredException ex) {
    logger.info(ex.getMessage());
    return "redirect:LogIn";
}

to catch Exception and the user will go to LoginPage instead of a exception error page

As Donal Boyle pointed , conclusion : use @SessionAttributes to share models between Controllers

Zakos
  • 1,492
  • 2
  • 22
  • 41
  • Fair enough on populating 'User' into the Session, but you don't want each & every Controller to be manually checking the user/ logged-in for proper security.. that kind of security check should be in a Filter, or common code somewhere. – Thomas W Jul 10 '13 at 09:48
  • How can that be achieved Thomas W – Abhishek Singh Apr 22 '14 at 10:29