springboot Filter Interceptor

  • interceptor
public class MyInterceptor1 implements HandlerInterceptor {
    //请求之前调用,如果该方法返回true会执行下一个Interceptor或Controller
    // 如果想要Controller继续执行最后一个Interceptor必需是true
    //如果第一个interceptor return true, 第二个return false 
    //第一个的afterCompletion会执行,但是第二个的不会,controller也不会执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Interceptor1 请求之前");
//        return false;
        return true;
    }

    //请求处理之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("Interceptor1 请求处理之后");
    }

    //视图渲染完毕(加载完css,js文件和el表达式)且当前Interceptor的preHandle返回是true时才会调用,主要用于抛异常
    //只要preHandle返回为true,无论被拦截的方法抛出异常与否都会执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("Interceptor1 视图处理完毕");
    }
}

  • controller
/**
 * Interceptor 只能对Controller请求进行拦截
 * Filter 对所有请求和响应拦截
 * 假如不在controller中filter会拦截, 但是interceptor不会拦截
 */
//@RestController
@Controller
public class MyController {
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        System.out.println("hello world");
        return "hello world";
    }

    /**
     * 返回模板引擎或是json,一次请求 filter和interceptor拦截一次
     */
    @RequestMapping("/test1")
    public String test1() {
        System.out.println("test1 执行");
        return "test1";
    }

    /**
     * 重定向发送两次请求,所以filter和Interceptor都会执行两次
     */
    @RequestMapping("/test2")
    public String test2(){
        System.out.println("test2 执行");
        //templates下的只能通过模板引擎访问到, 不能通过重定向或是请求转发访问到
        return "redirect:/test2.html";
    }

    /**
     * forward发送一次请求, 但是会被interceptor会执行两次(这里不明白不知道为什么会执行两次), filter执行一次
     */
    @RequestMapping("/test3")
    public String test3(){
        System.out.println("test3 执行");
        return "forward:/test3.html";
    }
}

猜你喜欢

转载自www.cnblogs.com/kikochz/p/12818222.html
今日推荐