SpringBoot拦截器
拦截器会对处理器进行拦截,这趟通过拦截器可以增强处理器的功能。
开发拦截器
所有的拦截器都需要实现HandlerInterceptor接口,在继承HandlerInterceptor有三个拦截器是经常使用的:
1.preHandle在业务处理器处理请求之前被调用
2.postHandle在业务处理器处理请求执行完成后,生成视图之前执行
3.afterCompletion在DispatcherServlet完全处理完请求后被调用该节都定义如下:
package com.example.demo.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @ Author wjw
* @ Date 2019-08-21
*/
public class Interceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception {
System.out.println("处理器前的方法");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) throws Exception {
System.out.println("处理器后的方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) throws Exception {
System.out.println("处理器完成的方法");
}
}
注册拦截器
package com.example.demo;
import com.example.demo.interceptor.Interceptor1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器到 springmvc 中,然后他会返回一个拦截器的注册
InterceptorRegistration ir = registry.addInterceptor(new Interceptor1());
// 指定拦截器的匹配模式,限制拦截器的拦截请求
ir.addPathPatterns("/interceptor/*");
}
}
拦截器控制
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ Author wjw
* @ Date 2019-08-21
*/
@RestController
@RequestMapping("/interceptor")
public class InterceptorController {
@RequestMapping("/start")
public String start() {
System.out.println("执行器处理逻辑");
return "hello world!";
}
}
来源:CSDN
作者:JayveeWong
链接:https://blog.csdn.net/weixin_42776111/article/details/104800314