开发者

Spring 3.0 set and get session attribute

I want to read a domain object (UserVO) from session scope.

I am setting the UserVO in a controller called WelcomeController

@Controller
@RequestMapping("/welcome.htm")
public class WelcomeController {
@RequestMapping(method = RequestMethod.POST)
    public String processSubmit(BindingResult result, SessionStatus status,HttpSession session){
      User user = loginService.loginUser(loginCredentials);
     session.setAttribute("user", user);
 开发者_Python百科        return "loginSuccess";
    }
}

I am able to use the object in jsp pages <h1>${user.userDetails.firstName}</h1>

But I am not able to read the value from another Controller,

I am trying to read the session attribute as follows:

@Controller
public class InspectionTypeController {
@RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
 public String addInspectionType(InspectionType inspectionType, HttpSession session)
 {
           User user = (User) session.getAttribute("user");
           System.out.println("User: "+ user.getUserDetails().getFirstName);

        }
} 


The code you've shown should work - the HttpSession is shared between the controllers, and you're using the same attribute name. Thus something else is going wrong that you're not showing us.

However, regardless of whether or not it works, Spring provides a more elegant approach to keeping your model objects in the session, using the @SessionAttribute annotation (see docs).

For example (I haven't tested this, but it gives you the idea):

@Controller
@RequestMapping("/welcome.htm")
@SessionAttributes({"user"})
public class WelcomeController {
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(ModelMap modelMap){
       User user = loginService.loginUser(loginCredentials);
       modelMap.addtAttribute(user);
       return "loginSuccess";
    }
}

and then

@Controller
@SessionAttributes({"user"})
public class InspectionTypeController {

   @RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
   public void addInspectionType(InspectionType inspectionType, @ModelAttribute User user) {
      System.out.println("User: "+ user.getUserDetails().getFirstName);
   }
} 

However, if your original code isn't working, then this won't work either, since something else is wrong with your session.


@SessionAttributes works only in context of particular handler, so attribute set in WelcomeController will be visible only in this controller.


Use a parent class to inherit all the controllers and use SessionAttributes over there. Just that this class should be in the package scan of mvc.


May be you have not set your UserVO as Serializable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜