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. 今天竟然有人模仿我的QQ号进行骗钱

    今天下午,CoderGeek同学告诉我,有个叫"小雷FansUnion"的QQ正在找他要钱,他直接和我这个正宗的"小雷FansUnion"探听虚实.这时才发现, ...

  2. spring-如何在项目启动的情况下获取Bean实例

    十年阿里,就只剩下这套Java开发体系了 >>>   大家都知道,项目启动的时候,spring读取xml文件,将配置的bean 或者 注解下的controller service d ...

  3. [Angular] Using useExisting provider

    Unlike 'useClass', 'useExisting' doesn't create a new instance when you register your service inside ...

  4. python开发环境设置(windows)

    python开发环境设置(windows) 1)  python2.7.3安装 在www.python.org上下载python-2.7.6.amd64.msi软件.安装完毕后设置path路径.控制面 ...

  5. Windows Phone 8.1 FilePicker API

    在 Windows Phone 8.1 中,增加了 FilePicker 的方式与文件打交道,最大的亮点在于这种方式不仅可以浏览手机上的文件,还可以浏览符合协议的应用里的文件! 比如点击 OneDri ...

  6. 【u211】编码

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 假设phi(W)得到是按照以下算法编码后的结果: 1. 如果W的长度为1那么phi(W)即为W: 2. ...

  7. 使用oschina的gitserver

    1.概要 事实上oschina的gitserver与github的几乎相同.只是既然是中国的gitserver,那么速度应该更快一些吧 2.注冊 链接https://git.oschina.net/, ...

  8. java中的subString具体解释及应用

    substring(參数)是java中截取字符串的一个方法 有两种传參方式 一种是public String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个 ...

  9. Wow6432Node(32位程序的注册表内容都在这个节点下,也可直接使用%systemroot%\syswow64\regedit进行编辑)

    64 位版本 Windows 中的注册表分为 32 位注册表项和 64 位注册表项.许多 32 位注册表项与其相应的 64 位注册表项同名,反之亦然. 64 位版本 Windows 包含的默认 64 ...

  10. 开源server软件

    Java缓存server jmemcached http://www.oschina.net/p/jmemcached jmemcached 是一个Java版的 memcached 缓存server, ...