0

我有一个简单的控制器和一个拦截器。
在 postHandle 方法的拦截器中,我正在检查用户。
问题:我的用户模型有时在控制器句柄之间为空。

  1. 由 home-handle==> User-Model 调用的 postHandle 不为空
  2. check_user-handle 调用的 postHandle ==>用户模型为空
  3. 由 redirectToErrorPage-handle ==> User-model 调用的 postHandle 不再为 null 并且包含我所期望的 check_user-PostHandle 调用的所有内容。

这是我的控制器

@Controller
@SessionAttributes("user")
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView home(Model model, HttpServletRequest request, HttpSession session) {

        User user = new User();
        return new ModelAndView("login", "user", user); 
        ////now User-Model was saved in the session
    }


    //now i'am redirectring user in the "check_user"-handle
    @RequestMapping(value = "/check_user", method = RequestMethod.POST)
    public ModelAndView checkUser(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model model,
            HttpServletRequest request, RedirectAttributes redirectAttr) {
        RedirectView redirectView = null;
        ModelAndView mav=null;
        try {       
            if(!bindingResult.hasErrors()){
                redirectView = new RedirectView("home");
                redirectView.setStatusCode(HttpStatus.FOUND);
                redirectAttr.addFlashAttribute("httpStatus", HttpStatus.FOUND);
                mav = new ModelAndView(redirectView);
                return mav; //at next i entry post-handle from interceptor,
                            //which says to me, that user-model is null.

            }
        }
    //My interceptor redirects me to this handle.
    //After this handle within interceptor method "postHandle", i see, that 
    //user-object exists
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String redirectToErrorPage(HttpServletRequest request){
        return "error";
    }
}

还有我的拦截器:

public class UserInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
        User user = (User) modelAndView.getModel().get("user");
        if(user == null || !user.isAdmin()){
            response.sendRedirect(request.getContextPath()+"/failed");
        }
    }
}

当我检索模型有哪些键时,当“check_user”调用 postHandle 时,我只有一个键“totalTime”。我的模型怎么了?

4

1 回答 1

0

尝试修改您postHandle()的如下:

...
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    User user = (User) request.getSession().getAttribute("user");
...
于 2017-04-13T06:08:38.703 回答