【问题标题】:Spring 3 MVC : move/share model from Controler to another ControlerSpring 3 MVC:从控制器到另一个控制器的视频/共享模型
【发布时间】:2011-08-15 15:04:14
【问题描述】:

我正在用 Spring 3 MVC 和 jQuery 做一个小项目

我不知道怎么问,所以我会试着解释一下

我有这种情况:

LoginPage(with User object model) ---submit--> 服务器将OK发送回LoginPage --> (LoginPage) 使用 window.location = "Page2" 重定向到 Page2

问题:第 2 页无法识别用户

如何让它发挥作用?我尝试阅读有关@SessionAttributes 的内容,但并没有真正理解。

@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
      ...
      ...

这里我希望从最后一个控制器中知道用户用户,但它正在创建一个新的。

@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将我的解决方案移至 Answers。

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    我的解决方案:

    @SessionAttributes("user")
    

    在两个控制器上

    @ModelAttribute("user") User user 
    

    作为方法中的参数 - 工作

    我也加了

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

    捕获异常,用户将转到 LoginPage 而不是异常错误页面

    正如 Donal Boyle 指出的那样,结论:使用 @SessionAttributes 在控制器之间共享模型

    【讨论】:

    • 将“用户”填充到会话中足够公平,但您不希望每个控制器都手动检查用户/登录以获得适当的安全性。这种安全检查应该在某个过滤器或公共代码中。
    • Thomas W 怎样才能做到这一点
    【解决方案2】:

    默认情况下,Spring MMVC 中的服务器端是无状态的。要在请求之间保存状态,您必须将要保存的数据放入会话中。然后,此数据可用于同一会话中的每个请求(即来自同一客户端)。

    在您找到的解决方案中,@SessionAttributes("user") 注释告诉 Spring MVC 您希望通过将用户对象保存在会话中来跨请求持久化。这就是 Spring 将您从自己实际维护状态的所有工作中抽象出来的方式。

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 2012-02-16
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多