2

我正在使用弹簧 mvc。因为我在登录时设置了会话属性。当用户登录时,我有一个搜索页面,他可以获得有关用户的更多详细信息。没有登录意味着他只能为此目的获得有限的详细信息我在登录表单中的@SessionAttributes 中设置会话对象,在用户搜索表单创建中我检查了会话属性是否具有值,如果不是意味着设置默认值。但是当我提交表单时,它显示错误 HTTP 状态

500 - Expected session attribute



 @RequestMapping(value = "/user-search", method = RequestMethod.GET)
    public String initUserSearchForm(Model model) {
        User user = new User();
        model.addAttribute("User", user);
        if(!model.containsAttribute("userObject"))
           model.addAttribute(createDefaultUserCredntials());
        return "user";
    }

@RequestMapping(value = "/user-byName", method = RequestMethod.GET)
    public
    @ResponseBody
    String getUserByName(HttpServletRequest request,@ModelAttribute("userObject")User user) {
       .... 
    ....
    } 

错误是

   org.springframework.web.HttpSessionRequiredException: Expected session attribute 'userObject'
        org.springframework.web.method.annotation.ModelFactory.initModel(ModelFactory.java:103)
        org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:723)
        org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
        org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
        org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
        org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
        org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
4

2 回答 2

10

因为您已声明为 sessionattribute,所以在调用控制器时,您应该在 session 中提供 userObject 属性。将其作为 ModelAttribbute 返回,它将正常工作。将以下代码添加到您的控制器

@ModelAttribute("userObject")
    public UserObject getUserObject() {
        return new UserObject();

    }
于 2013-07-19T04:39:07.440 回答
2

您在代码中的何处设置“userObject”。我没有在你的代码中看到。根据您在表单初始化中设置的报价

 @RequestMapping(value = "/user-search", method = RequestMethod.GET)
    public String initUserSearchForm(Model model) {
        User user = new User();
        model.addAttribute("User", user);
        if(!model.containsAttribute("userObject"))
           model.addAttribute('userObject',createDefaultUserCredntials());
        return "user";
    }

你必须像这样使用,model.addAttribute('userObject',createDefaultUserCredntials());否则它只在模型中而不是在会话中设置

于 2013-07-19T05:02:15.140 回答