前言
现在有一个需求场景:每一个请求我都需要在请求头里面加上token这个请求头,作为一种校验机制,传统的接口可以通过设置一个全局的变量,然后通过页面携带过来(大概就是先将我们的token放在session中,写一个服务用来获取session中的token,然后主页面用 ajax 调用接口,将 token放在隐藏域中,然后将请求头放进来,用 ajax 方法,这里不想细说了),但是有一个情况是通过页面传递的并不一定都会适用所有接口,比如上传和下载的接口有时候请求头里面就没有token 参数,可能是上传和下载是用表单提交的。
这个时候如何将请求头通过后台的方法加进来?
想到用过滤器,用后台方法强制加入请求头。
我这里加的是将用户唯一标识加在请求头上,并在自己需要的时候自己获取
1.创建拦截器,核心代码为 addHeader方法,将userid添加到请求头中
package com.kaying.luck.interceptor;
import com.kaying.luck.dao.draw.user.UserDao;
import com.kaying.luck.exception.ServiceException;
import com.kaying.luck.pojo.draw.user.dos.UserDO;
import com.kaying.luck.response.enums.ApiResponseCodeEnum;
import com.kaying.luck.utils.applicationContext.MyApplicationContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.beans.factory.annotation.Autowired;
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.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* @author csp
* @create 2021-11-23 14:54
* @description
*/
@Component
public class BaseInterceptor implements HandlerInterceptor {
@Autowired
private UserDao userDao = MyApplicationContext.getBean(UserDao.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String userId = request.getHeader("userId");
if (StringUtils.isBlank(userId)){
throw new ServiceException(ApiResponseCodeEnum.ERROR_USER_ID, "未查询到用户信息");
}
UserDO userDO = userDao.getUserByUserId(userId);
if (userDO == null) {
userDO = new UserDO();
userDO.setId(null);
userDO.setUserId(userId);
userDO.setUserOrderStatus(0);
userDao.insert(userDO);
}
Map<String,String> map=new HashMap<>();
map.put("userId",userId);
addHeader(request,map);
return true;
}
private void addHeader(HttpServletRequest request, Map<String, String> headerMap) {
if (headerMap==null||headerMap.isEmpty()){
return;
}
Class<? extends HttpServletRequest> c=request.getClass();
//System.out.println(c.getName());
System.out.println("request实现类="+c.getName());
try{
Field requestField=c.getDeclaredField("request");
requestField.setAccessible(true);
Object o=requestField.get(request);
Field coyoteRequest=o.getClass().getDeclaredField("coyoteRequest");
coyoteRequest.setAccessible(true);
Object o2=coyoteRequest.get(o);
System.out.println("coyoteRequest实现类="+o2.getClass().getName());
Field headers=o2.getClass().getDeclaredField("headers");
headers.setAccessible(true);
MimeHeaders mimeHeaders=(MimeHeaders) headers.get(o2);
for (Map.Entry<String,String> entry:headerMap.entrySet()){
mimeHeaders.removeHeader(entry.getKey());
mimeHeaders.addValue(entry.getKey()).setString(entry.getValue());
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2.配置拦截器,拦截器需要配置才能使用
package com.kaying.luck.config.interceptor;
import com.kaying.luck.interceptor.BaseInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 拦截器需要配置才可以使用,也可以在这里注入其他的类
*
* @author yt
* @create 2022/10/17 14:26
*/
@Configuration
public class BaseInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器
registry.addInterceptor(new BaseInterceptor())
//添加拦截路径
.addPathPatterns("/**")
//排除的拦截路径(此路径不拦截)
.excludePathPatterns("/swagger/**","/error","/download/**","/wx/**","/address/**","/management/**","/callback/**",
"/favicon.ico","/swagger2/**", "/swagger*", "/swagger*/**", "/webjars/**", "/doc.html", "/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs**");
}
/**
* 开启跨域
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOriginPatterns("*")
// 是否允许证书(cookies)
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 跨域允许时间
.maxAge(3600);
}
}
4.在要拦截的方法接收参数上添加 @RequestHeader注解
@ApiOperation(value = "根据用户UserId查询用户信息")
@GetMapping("get/user")
public ApiResponse<UserDO> getUserByUserId( @RequestHeader("userId") String userId) {
System.out.println("userId = " + userId);
if (StringUtils.isBlank(userId)) {
throw new ServiceException(ApiResponseCodeEnum.FAIL, "获取用户信息失败");
}
UserDO userDO = userLoginService.getUserByUserId(userId);
return ApiResponse.success(userDO);
}
5.测试访问是可以拿到userid的文章来源:https://www.toymoban.com/news/detail-533222.html
文章来源地址https://www.toymoban.com/news/detail-533222.html
到了这里,关于java在过滤器中为http请求加请求头header的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!