Springboot implements interceptor to get header content
A requirement was encountered in the project. The connection to the upstream system involves the need to add a request header. The information in the request header is dynamically obtained and needs to be dynamically obtained from the downstream and then transferred to the upstream.
analyze
Since it needs to be obtained dynamically, there are only two ways: either obtain it from the request header every time a downstream request comes, or define a unified interceptor to obtain it automatically.
accomplish
So let's implement it first.
The first one is relatively simple, directly using springboot to get the request header, and use it from the controller method entry: @RequestHeader(value = "xxxx", required = false) String appUser way to get the request header
code show as below:
@RequestMapping(name = "获取用户详情信息",value = "/getUserDetail",method=GET)
public String getUserDetail(@RequestHeader(value = "app-user",required = false) String appUser, @RequestParam(name = "search") String search){
log.info("------>拿到的请求头是:"+appUser);
return "SUCCESS";
}
Although this method can be obtained, it is too low b, and if there are dozens of interfaces, it must be written like this, which is too cumbersome
Or use the interceptor way
details as follows:
First, to define an interceptor, you need to implement HandlerInterceptor, which includes preHandler and afterCompletion corresponding to before calling and after calling.
package com.xxxx.cc.admin.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.ddmc.cc.admin.support.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Copyright (C), 2017-2021
* Author: sjugg
* Date: 2021/5/19 10:39
* FileName: AuthInterceptor
* Description: 交易前置拦截器
*/
@Component
@Slf4j
public class AuthInfoInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userInfo = request.getHeader("app-user");
log.info(">>>>>>>拦截到api相关请求头<<<<<<<<"+userInfo);
if(StringUtils.isNotEmpty(userInfo)){
//直接搂下来,放到ThreadLocal中 后续直接从中获取
ThreadLocalUtils.set(MaiCaiApiConstants.MAI_CAI_APP_USER,userInfo);
}
return true;//注意 这里必须是true否则请求将就此终止。
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//移除app-user
ThreadLocalUtils.remove("app-user");
log.info("移除请求头中的app-user:"+ThreadLocalUtils.get("app-user"));
}
}
Later, just press the key from ThreadLocal to get it.
The other thing to do is
add web filter
1. Add web filters, manage filtered classes, and filtered request paths
2. Inherit the WebMvcConfigurationSupport class and generate as above, and rewrite the method addInterceptors of the parent class
3. Intercept classes through registry.addInterceptor, addPathPatterns intercept paths, and excludePathPatterns add allowed paths
Here I intercept requests starting with xxxx.
package com.ddmc.cc.admin.config;
import com.ddmc.cc.admin.interceptor.AuthInfoInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
*
*
* @author sjugg
* @since 2021/5/13 4:43 下午
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private AuthInfoInterceptor authInfoInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInfoInterceptor).addPathPatterns("/xxxx/*");
}
}
The execution effect is as follows :
Set app-user information in the request header
You can see that the information in the request header has been obtained in the Controller
Get the code of the head:
@RequestMapping(name = "获取用户详情信息",value = "/getUserDetail",method=GET)
public String getUserDetail(@RequestParam(name = "search") String search){
log.info("-----> heard info here: "+ThreadLocalUtils.get("app-user"));
return "SUCCESS";
}
After the method is executed, the corresponding threadlocal variable is also cleared