java – Spring 3.0设置并获取会话属性

我想从会话范围读取域对象(UserVO).

我将UserVO设置在名为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);
         return "loginSuccess";
    }
}

我可以在jsp页面< h1> ${user.userDetails.firstName}< / h1>中使用该对象.

但是我无法读取另一个控制器的值,

我正在尝试读取会话属性如下:

@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);

        }
} 
您显示的代码应该可以工作 – HttpSession在控制器之间共享,并且您使用相同的属性名称.因此,您没有向我们展示其他问题.

但是,无论它是否工作,Spring使用@SessionAttribute注释(见docs)提供了一种更优雅的方法来保持模型对象在会话中.

例如(我没有测试过这个,但它给了你这个想法):

@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";
    }
}

接着

@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);
   }
} 

但是,如果您的原始代码不工作,那么这也不会奏效,因为会话中有其他问题.

http://stackoverflow.com/questions/2227395/spring-3-0-set-and-get-session-attribute

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – Spring 3.0设置并获取会话属性