springboot 配置拦截器
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 配置拦截器的更多相关文章
- SpringBoot配置拦截器
[配置步骤] 1.为类添加注解@Configuration,配置拦截器 2.继承WebMvcConfigurerAdapter类 3.重写addInterceptors方法,添加需要拦截的请求 @Co ...
- SpringBoot——配置类实现WebMvcConfigurer接口来配置拦截器、view-controller、视图解析器等
目的:为了保留SpringBoot对SpringMVC自动配置,另外我们还想要做一些自己拓展的功能 如何做扩展? 以配置view-controller实现跳转为例: 原先在SpringMvc中我们写v ...
- springboot的拦截器Interceptor的性质
Interceptor在springboot2.x版本的快速入门 实现HandlerInterceptor的接口,并重载它的三个方法:preHandle.postHandle.afterComplet ...
- SpringBoot MVC 拦截器
SpringBoot MVC 环境搭建 在pom.xml添加spring-boot-starter-web <dependency> <groupId>org.spri ...
- SpringBoot使用拦截器
SpringBoot的拦截器只能拦截流经DispatcherServlet的请求,对于自定义的Servlet无法进行拦截. SpringMVC中的拦截器有两种:HandlerInterceptor和W ...
- springboot+springmvc拦截器做登录拦截
springboot+springmvc拦截器做登录拦截 LoginInterceptor 实现 HandlerInterceptor 接口,自定义拦截器处理方法 LoginConfiguration ...
- SpringMVC拦截器与SpringBoot自定义拦截器
首先我们先回顾一下传统拦截器的写法: 第一步创建一个类实现HandlerInterceptor接口,重写接口的方法. 第二步在XML中进行如下配置,就可以实现自定义拦截器了 SpringBoot实现自 ...
- spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项
原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.o ...
- SpringBoot自定义拦截器实现IP白名单功能
SpringBoot自定义拦截器实现IP白名单功能 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8993331.html 首先,相关功能已经上线了,且先让我先 ...
随机推荐
- php 时间戳转为多少分钟前 小时前 天前
function mdate($time = NULL) { $text = ''; $time = $time === NULL || $time > time() ? time() : in ...
- 数据类型总结——String(字符串类型)
相关文章 简书原文:https://www.jianshu.com/p/546a755c3eb6 数据类型总结——概述:https://www.cnblogs.com/shcrk/p/9266015. ...
- 【u116】最短路计数
Time Limit: 1 second Memory Limit: 128 MB [问题描述] 给出一个N个顶点M条边的无向无权图,顶点编号为1-N.问从顶点1开始,到其他每个点的最短路有几条. [ ...
- 【24.91】【Tsinsen 1302】&【BZOJ 2626】JZPFAR
时间限制:5.0s 内存限制:256.0MB 总提交次数:547 AC次数:137 平均分:40.31 将本题分享到: 查看未格式化的试题 提交 试题讨论 试题来 ...
- [React Native] Animate Styles of a React Native View with Animated.timing
In this lesson we will use Animated.timing to animate the opacity and height of a View in our React ...
- 单个和多个checkbox选中事件怎么写
单个和多个checkbox选中事件怎么写 一.总结 一句话总结: 1.checkbox的事件方法的话主要是change和click 2.checkbox的属性判断的话主要是prop(判断checked ...
- Redis数据存储解决方案
http://www.tuicool.com/articles/77nUZn 1.背景 1.1 Redis简介 官方网站: http://redis.io/ ,Redis是REmote DIction ...
- Eclipse 一直不停 building workspace... 完美解决总结
Eclipse 一直不停 building workspace... 一.产生这个问题的原因多种 1.自动升级 2.未正确关闭 3.maven下载lib挂起 等..二.解决总结 (1).解决方法 ...
- KMP算法具体解释(贴链接)
---------------------------------------------------------------------------------------------------- ...
- 华为云软件开发云:容器DevOps,原来如此简单!
当开发团队把代码提交到 Git 应用仓库的那一刻,他们心里在想什么? 祈祷没有bug?渴望回家补觉?产品经理Go Die? 对,也不对.因为这只是最终发布万里长征的一小步,接下来要面对测试环境.生产环 ...