Solution of interceptor Interceptor Not Effective in spring boot
- 2021-11-14 05:51:20
- OfStack
interceptor Interceptor Not Effective
The interceptor was found to be not effective when building the project
Start with spring boot version 1.5. 6
The code is as follows:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
private TimeInterceptor timeInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.timeInterceptor);
super.addInterceptors(registry);
}
}
@Component
public class RequestParamInfoIntorceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(RequestParamInfoIntorceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
try {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String beanName = handlerMethod.getBean().getClass().toString();// Class
String methodName = handlerMethod.getMethod().getName();// Method name
if(methodName.equals("error") || methodName.equals("success")) {
return super.preHandle(request, response, handler);
}
String uri = request.getRequestURI();// Request path
String remoteAddr = getIpAddr(request);//ip
String method = request.getMethod(); // Request mode
Map<String,String[]> pramMap = request.getParameterMap();
StringBuffer sbf = new StringBuffer();
int count = 0;
String forCunt = "";
for(Map.Entry<String, String[]> entry:pramMap.entrySet()){
forCunt = "[" + count + "]" + " : " ;
sbf.append( "paramName" + forCunt + entry.getKey() + " - "+ "paramValue" +
forCunt + request.getParameter(entry.getKey()) + "\n");
count ++;
}
logger.info(" { beanName : " + beanName + " | " + "methodName : " + methodName + " | " + "uri : "
+ uri + " | " + "remoteAddr : " + remoteAddr + " | " + "requestMethod : " +
method + "\n" + "param : " + sbf + "}");
}
} catch (Exception e) {
// Error
logger.error(e.toString());
}
return super.preHandle(request, response, handler);
}
// Get client IP
private String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
I thought it was a version problem at first, and then upgraded to 2.1. 1, and WebConfig was changed to implement WebMvcConfigurer. The code is as follows
@Configuration
@Component
public class WebConfig implements WebMvcConfigurer{
@Autowired
private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
}
}
After verification, it is still not possible. After continuing to check, it is found that when adding version control, some configuration classes inherit WebMvcConfigurationSupport. Query WebMvcConfigurationSupport source code and find that there is interceptor registration method addInterceptors (InterceptorRegistry registry), so rewrite this method in version control configuration class to add interceptor, interceptor takes effect and problem is solved.
Solutions
The code is as follows:
@Configuration
public class ApiConfig extends WebMvcConfigurationSupport {
@Autowired
private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
HandlerInterceptor realizes login failure interception and so on
First write a class that implements HandlerInterceptor
The code is as follows:
public class SessionInterceptor implements HandlerInterceptor {
@Autowired
RedisTemplate<String, String> redisTemplate;
//private static String LOGIN_CODE = "/user/no_loginPage?Landingcode=" + UserResourcesHelper.LANDINGCODE_106;// Login address and code Information
//private static String LOGIN_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri=&response_type=code&scope=snsapi_userinfo&state=1234#wechat_redirect";
protected List<String> patterns = new ArrayList<String>(Arrays.asList(".*?/.*/no_.*?", "/", "/error"));
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 1 Some methods that don't need filtering
String url = request.getRequestURI();
if (isInclude(url) == true)
return true;
// Permission verification
Cookie cookie = getCookieByName(request, UserResourcesHelper.COOKIE_TOKEN_NAME);
String user = null;
if (cookie != null && !cookie.getValue().equals("")) {
user = redisTemplate.opsForValue().get(RedisKeyConstant.USER_WEB_TOKEN + cookie.getValue());
}
if (cookie == null || user == null) {// Determine whether the user has been authorized
// Determine whether it is AJAX Visit
if (request.getHeader("x-requested-with") != null
&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
response.setHeader("sessionstatus", "timeout");
response.setStatus(403);
return false;
} else {
response.sendRedirect(request.getContextPath()+"/home/no_index_toLoginSkip");
//response.sendRedirect(request.getContextPath() +UserResourcesHelper.LOGIN_URL); // Non AJAX Access, page jump
//response.sendRedirect(request.getContextPath() +"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri="+URLEncoder.encode("http://m.hobay.cn/user/no_loginPage", "utf-8")+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect"); // Non AJAX Access, page jump
return false;
}
}
return true;
}
@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 boolean isInclude(String url) {
for (String pattern : patterns) {
if (Pattern.matches(pattern, url)) {
return true;
}
}
return false;
}
/**
* Get by name cookie
*
* @param request
* @param name
* cookie Name
* @return
*/
private static Cookie getCookieByName(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = ReadCookieMap(request);
if (cookieMap.containsKey(name)) {
Cookie cookie = (Cookie) cookieMap.get(name);
return cookie;
} else {
return null;
}
}
/**
* Will cookie Encapsulate to Map Inside
*
* @param request
* @return
*/
private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
Then register this interceptor in spring
The code is as follows:
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
SessionInterceptor sessioninterceptor() {
return new SessionInterceptor();
}
/**
* Configure interceptor
* @author yuqingquan
* @param registry
*/
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(sessioninterceptor());
}