一、应用场景
一般前后端分离的项目需要处理跨域问题,如果在拦截器中做的话可以,但是会有一些路径不进行拦截,比如登陆,token换取等等,但是呢,如果这些路径设置了不进行拦截如下所示:
注入类:
@Configuration public class MyIntercepterConfig implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { // TODO Auto-generated method stub registry.addInterceptor(new MyIntercepter()).addPathPatterns("/**").excludePathPatterns("/login/login"); } }
public class MyIntercepter implements HandlerInterceptor { private static final Logger logger = LoggerFactory.getLogger(MyIntercepter.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 处理跨域 // 身份认证 // TODO Auto-generated method stub return true; } }
但是呢,这些路径放弃拦截后,无法处理跨域了,也可以写一个过滤器来处理跨域问题,但是如果想用一个拦截器来搞定呢?此时就可以使用自定义注解了
二、应用
将自定义的注解放到不进行拦截的类上即可,代码如下:
注解类:
/** * * @version: 1.1.0 * @Description: 免登陆注解 * @author: wsq * @date: 2020年6月29日下午8:30:07 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface NotLogin { }
controller层:
/** * * @version: 1.1.0 * @Description: 控制层 * @author: wsq * @date: 2020年6月25日下午8:56:44 */ @RestController public class LogTestController { @GetMapping("/logTest") public String logTest(@RequestParam("id") int id, @RequestParam("name") String name) { System.out.println("id:" + id + " " + "name:" + name); return id+name; } @NotLogin @GetMapping("/logTest2") public String logTest2(@RequestParam("id2") int id, @RequestParam("name2") String name) { System.out.println("id2:" + id + " " + "name2:" + name); return id+name; } }
注解类:
@Configuration public class MyIntercepterConfig implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { // TODO Auto-generated method stub registry.addInterceptor(new MyIntercepter()).addPathPatterns("/**"); } }
private static final Logger logger = LoggerFactory.getLogger(MyIntercepter.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 跨域处理 HandlerMethod handlerMethod = (HandlerMethod) handler; NotLogin notLogin = handlerMethod.getMethod().getAnnotation(NotLogin.class); if (notLogin != null) { return true; } // 身份认证 // TODO Auto-generated method stub return true; }
搞定
@Configurationpublic class MyIntercepterConfig implements WebMvcConfigurer{@Overridepublic void addInterceptors(InterceptorRegistry registry) {// TODO Auto-generated method stubregistry.addInterceptor(new MyIntercepter()).addPathPatterns("/**");}}