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. Tidhy

    JavaBean.hbm.xml(hibernate配置方面的): <?xml version="1.0" encoding="UTF-8"?> & ...

  2. 使用ionic3快速开发webapp(二)

    本文整理了使用ionic3开发时会用到的一些最基本组件及用法 1.ion-tabs 最常见的通过标签切换页面: tabs.html <ion-tabs> <ion-tab [root ...

  3. POJ 1751 Highways (ZOJ 2048 ) MST

    http://poj.org/problem?id=1751 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2048 题目大 ...

  4. IntelliJ IDEA设置鼠标悬浮提示

    测试代码; public interface MyInterface { /** * 我是接口方法的注释 * @param num1 我是接口方法入参的注释 * @return 我是接口方法返回值的注 ...

  5. XHTML 结构化:使用 XHTML 重构网站 分类: C1_HTML/JS/JQUERY 2014-07-31 15:58 249人阅读 评论(0) 收藏

    http://www.w3school.com.cn/xhtml/xhtml_structural_01.asp 我们曾经为本节撰写的标题是:"XHTML : 简单的规则,容易的方针.&qu ...

  6. 在线算法与离线算法(online or offline)

    1. 在线算法(online) PFC(prefix-free code)编码树的解码过程:可以在二进制编码串的接收过程中实时进行,而不必等到所有比特位都到达后才开始: 2. 离线算法(offline ...

  7. 在VS2015中用C++创建DLL并用C++调用且同一时候实现对DLL的调试

    一:用C++创建DLL            依照[在VS2015中用C++编写可被其他语言调用的动态库DLL]提示创建C++编写的DLL.或參考[在VS2015中用C++创建DLL并用C#调用且同一 ...

  8. 以Graphicslayer为管理组来管理Element.

    转自原文 以Graphicslayer为管理组来管理Element. 前言 在AE开发过程中,我们经常使用Element(元素).它的出现让地图与用户之间的交互增加了不少的效果.在地图上,可以通过各种 ...

  9. Android Gradle Plugin指南(三)——依赖关系、android库和多项目配置

    原文地址:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Dependencies-Android-Librari ...

  10. 【codeforces 762A】k-th divisor

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