需求背景
在项目中需要全局拦截用户请求,针对一些特定请求,可进行特殊业务处理和请求过滤
技术点
主要使用了两个对象
1. HandlerInterceptorAdapter对象(org.springframework.web.servlet.handler.HandlerInterceptorAdapter)
2. WebMvcConfigurationSupport对象(org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport)
对于第2点,不同于SpringBoot2中,SpringBoot1使用的是WebMvcConfigurerAdapter对象(org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter)
案例说明
场景案例分析:
1. 拦截所有请求,对特定请求可以进行特殊处理和过滤
2. 可对一批请求,验证固化的一些请求参数
3. 有时需要在拦截器中注入服务层对象,调用业务相关逻辑方法
4. 开启跨域请求访问功能
代码演示
举两个例子
1. 定义拦截器,拦截所有请求
WebConfig类
package com.md.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 拦截器定义
*
* @author Minbo.He
*/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
/**
* 可定义多个拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 定义过滤拦截的url名称,拦截所有请求
registry.addInterceptor(new MyHttpInterceptor()).addPathPatterns("/**");
// registry.addInterceptor(其他拦截器).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
MyHttpInterceptor类
package com.md.demo;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* 拦截处理类
*
* @author Minbo.He
*/
@Component
public class MyHttpInterceptor extends HandlerInterceptorAdapter {
protected static Logger logger = LoggerFactory.getLogger(MyHttpInterceptor.class);
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = "";
// 去掉最后一个空格
Map<String, String[]> params = request.getParameterMap();
for (String key : params.keySet()) {
String[] values = params.get(key);
for (int i = 0; i < values.length; i++) {
String value = values[i];
queryString += key + "=" + value + "&";
}
}
queryString = queryString.equals("") ? null : queryString.substring(0, queryString.length() - 1);
logger.info(String.format("请求参数, url: %s, method: %s, params: %s", url, method, queryString));
// hello不做拦截
if (uri.equals("/hello")) {
return true;
}
// 其他拦截请求(请求必须都带上用户id)
String userId = request.getParameter("userId");
if (userId != null) {
return true;
} else {
this.output(response, "{\n"
+ "\"code\": \"4001\",\n"
+ "\"message\": \"参数错误\"\n"
+ "}");
return false;
}
}
/**
* 输出结果
*/
private void output(HttpServletResponse response, String result) throws Exception {
response.setHeader("content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println(result);
}
}
2. 开启跨域请求访问功能
package com.md.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 程序主入口
*
* @author Minbo
*
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* 开启过滤器功能
*
* @return
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
/**
* 跨域过滤器
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
完整源码下载
https://github.com/hemin1003/spring-boot-study/tree/master/spring-boot2-study/spring-boot2-parent
下一章教程
SpringBoot从入门到精通教程(三)- RocketMQ集成和场景案例分析
该系列教程
------------------------------------------------------
------------------------------------------------------
关于我(个人域名)
期望和大家一起学习,共同进步,共勉,O(∩_∩)O谢谢
欢迎交流问题,可加个人QQ 469580884,
或者,加我的群号 751925591,一起探讨交流问题
不讲虚的,只做实干家
Talk is cheap,show me the code
如果觉得内容赞,您可以请我喝杯咖啡: