【spring boot】spring boot 拦截器
今日份代码:
1.定义拦截器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Spring boot拦截器
*/
@Component
public class MyInterceptor implements HandlerInterceptor {
private final static Logger log = LoggerFactory.getLogger(MyInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean pass = true;
String methodType = request.getMethod(); //GET 或 POST
String url = request.getRequestURI();
String 入参值1 = request.getParameter("接口入参1");
if (!pass) {
response(request,response,"未通过拦截器校验");
}
return pass;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
//返回拦截消息给前端,解决跨域,编码问题
private void response(HttpServletRequest request, HttpServletResponse response, String message) throws Exception{
String origin = request.getHeader("Origin");
if (StringUtils.isNotBlank(origin)) {
if (origin.toLowerCase().indexOf(".XXX.com") > 0) {
response.setHeader("Access-Control-Allow-Origin", origin); // 允许访问的域
response.setHeader("Access-Control-Allow-Methods", "POST,GET");// 允许GET、POST的外域请求
response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许请求带cookie到服务器
response.setContentType("text/html; charset=utf-8"); // 设定JSON格式标准输出、及编码
}
}
PrintWriter pw = response.getWriter();
pw.write(JSON.toJSONString(message));
pw.flush();
pw.close();
}
}
2.注册拦截器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.annotation.Resource;
/**
* 拦截器配置
*/
@ControllerAdvice
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Resource
private MyInterceptor myInterceptor;
@Resource
private MyInterceptor2 myInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//多个拦截器 按照代码顺序 从上到下先后进入
registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/XXX/111","/YYY/222");
registry.addInterceptor(myInterceptor2).addPathPatterns("/**");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
3.扫描拦截器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
启动类上需要保证 拦截器定义的位置 可以被Spring扫描到:
@SpringBootApplication
@ComponentScan(basePackages = {"com.XX.*", "com.YY.*"})