Spring MVC - 在构造函数中重定向

时间:2013-01-31 06:58:54

标签: java spring redirect spring-mvc

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

例如:在构造函数内部,我需要检查一些条件,如果没有遇到,我想重定向到其他地方。同样,构造函数的其余部分也不会执行"原始跟随操作"。我想要这样的代码。

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

   ...rest code...
}

修改

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

1 个答案:

答案 0 :(得分: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>