2

如果需要,我想知道如何在控制器构造函数中重定向请求?

例如:在构造函数中,我需要检查一些条件,如果不满足,我想重定向到其他地方。同样,构造函数的其余部分也不会执行“原始后续操作”。我想要这样的代码。

@Controller
class SampleController{
   public SampleController(){
      if(![some condition]){
         ...redirecting code...
      }
      ...rest code...
   }

   ...rest code...
}

编辑

如果构造函数不是一个好的选项或方法,那么是否有任何选项像过滤器之前将始终在构造函数的每个操作之前执行并且会在某些条件失败时重定向?

4

1 回答 1

3

您可以使用拦截器:

public class CheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
        if (handler instanceof TheController) {
        // or for any controller: if (handler.getClass().isAnnotationPresent(Controller.class))
            if (!check()) {
                redirect("/check-failure.html");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private void redirect(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
        try {
            response.sendRedirect(request.getContextPath() + path);
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

    private boolean check() {
        return ...
    }

}

然后在 applicationContext.xml 中注册它:

<mvc:interceptors>
    <bean class="your.package.CheckInterceptor" />
</mvc:interceptors>
于 2013-01-31T09:13:11.450 回答