1 有这样一个需求

服务端对部分请求URL需要验证身份。如果验证错误,停止请求,按照既定的数据格式返回;如果验证正确,继续执行请求。

2 需要这样做

1. 将指定格式的请求拦截下来;

2. 获取参数,验证参数;

3. 验证不通过,返回既定数据格式。

3 步骤

  需要对参数进行逻辑操作,所以需要在拦截器中注入实例,返回的数据是指定格式,所以要重写response

1.定义拦截器,要继承HandlerInterceptorAdapter ,重写“处理请求前”方法,在该方法中进行逻辑验证。

代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.boco.osmp.entities.TokenOriginEntity;
import com.boco.osmp.model.TokenModel; import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
*
*
* @author
*
*/
public class CommonInterceptor extends HandlerInterceptorAdapter {
@Autowired
private TokenModel tokenModel; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { String requestUri = request.getRequestURI();
String contextPath = request.getContextPath();
String url = requestUri.substring(contextPath.length()); if ("GET".equalsIgnoreCase(request.getMethod()) || "POST".equalsIgnoreCase(request.getMethod())) {
if (url.contains("/api/")) {
String token = request.getHeader("authorization");
String userId = request.getParameter("userId");
if (token != null && userId != null) {
String tokenSource = tokenModel.getToken(userId);
// 如果token验证不通过,返回已经登录的用户信息
if (!token.equals(tokenSource)) {
String p = tokenModel.decryptTokenToResponse(tokenSource, TokenOriginEntity.class);
response.setContentType("application/json;charset=utf-8");
PrintWriter writer;
writer = response.getWriter();
writer.write(p);
return false;
}
} else {
throw new Exception("token或 用户ID不能为空");
}
}
return true;
} else {
throw new Exception("不支持的请求类型!");
} }
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
} @Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
super.afterConcurrentHandlingStarted(request, response, handler);
}
}

拦截器中需要写的是,如果验证错误,需要返回既定格式数据,

是这几行代码实现的

 response.setContentType("application/json;charset=utf-8"); //JSON
PrintWriter writer;
writer = response.getWriter();
writer.write(p); //数据

2. 重写配置文件,添加新增的拦截器

在配置文件中需要实例化一个拦截器,这样才能保证在拦截器中注入的实例有效。

swagger U的默认地址也需要手动添加进去。

代码

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.boco.osmp.interceptor.CommonInterceptor; /**
* 配置拦截器
* 初始化拦截器,这样在拦截器中可以注入@service
* @author
*/
@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter { /**
* 需要重新该方法,将swagger-ui.html手动加入,否则会请求不到
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
} @Bean
public CommonInterceptor interceptor() {
return new CommonInterceptor();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}

springboot 配置拦截器的更多相关文章

  1. SpringBoot配置拦截器

    [配置步骤] 1.为类添加注解@Configuration,配置拦截器 2.继承WebMvcConfigurerAdapter类 3.重写addInterceptors方法,添加需要拦截的请求 @Co ...

  2. SpringBoot——配置类实现WebMvcConfigurer接口来配置拦截器、view-controller、视图解析器等

    目的:为了保留SpringBoot对SpringMVC自动配置,另外我们还想要做一些自己拓展的功能 如何做扩展? 以配置view-controller实现跳转为例: 原先在SpringMvc中我们写v ...

  3. springboot的拦截器Interceptor的性质

    Interceptor在springboot2.x版本的快速入门 实现HandlerInterceptor的接口,并重载它的三个方法:preHandle.postHandle.afterComplet ...

  4. SpringBoot MVC 拦截器

    SpringBoot MVC 环境搭建 在pom.xml添加spring-boot-starter-web   <dependency>   <groupId>org.spri ...

  5. SpringBoot使用拦截器

    SpringBoot的拦截器只能拦截流经DispatcherServlet的请求,对于自定义的Servlet无法进行拦截. SpringMVC中的拦截器有两种:HandlerInterceptor和W ...

  6. springboot+springmvc拦截器做登录拦截

    springboot+springmvc拦截器做登录拦截 LoginInterceptor 实现 HandlerInterceptor 接口,自定义拦截器处理方法 LoginConfiguration ...

  7. SpringMVC拦截器与SpringBoot自定义拦截器

    首先我们先回顾一下传统拦截器的写法: 第一步创建一个类实现HandlerInterceptor接口,重写接口的方法. 第二步在XML中进行如下配置,就可以实现自定义拦截器了 SpringBoot实现自 ...

  8. spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项

    原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.o ...

  9. SpringBoot自定义拦截器实现IP白名单功能

    SpringBoot自定义拦截器实现IP白名单功能 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8993331.html 首先,相关功能已经上线了,且先让我先 ...

随机推荐

  1. NYOJ 364 田忌赛马

    田忌赛马 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描写叙述 Here is a famous story in Chinese history. "That ...

  2. [内核编程] 4.5 HOOK分发函数

    4.5 HOOK分发函数 本节开始深入的探讨键盘的过滤与反过滤.有趣的是,无论是过滤还是反过 滤,其原理都是进行过滤.取胜的关键在于:谁将第一个得到信息. 黑客可能会通过修改一个已经存在的驱动对象(比 ...

  3. 【45.65%】【codeforces 560B】Gerald is into Art

    time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  4. STS 3.6.4 SpringMVC 4.1.6 Hibernate 4.3.8 MySQL

    开发环境: Java 1.8 Spring Tool Suite 3.6.4 Spring faramework 4.1.6 Hibernate 4.3.8 Maven 2.9 数据库是MySQL 5 ...

  5. js进阶 11-14 jquery如何实现元素的替换和遍历

    js进阶  11-14  jquery如何实现元素的替换和遍历 一.总结 一句话总结:替换:replaceAll() 与 replaceWith().遍历:each(). 1.replaceAll() ...

  6. 常用JS验证函数总结

    JS验证Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/- ...

  7. 【u026】房间最短路问题

    描述 在一个长宽均为10,入口出口分别为(0,5).(10,5)的房间里,有几堵墙,每堵墙上有两个缺口,求入口到出口的最短路经. 格式 输入格式 第一排为n(n<=20),墙的数目. 接下来n排 ...

  8. Qt 通过绘画设置边框阴影

    首先widget设置 setWindowFlags(Qt::FramelessWindowHint); setAttribute(Qt::WA_TranslucentBackground, true) ...

  9. Linux中export导入环境变量的几种方式

    1.首先类似于windows中的设定系统环境变量的方式为,在/etc/profile中 export PATH=$PATH:....:... 注意间隔符为: 然后复用原来路径是$PATH的方式 2.用 ...

  10. 毕设二:python 爬取京东的商品评论

    # -*- coding: utf-8 -*- # @author: Tele # @Time : 2019/04/14 下午 3:48 # 多线程版 import time import reque ...