Springboot实现拦截器获取header内容

1、利用注解

第一种方式比较简单,直接使用springboot获取请求头的方式,从controller方法入口处使用: @RequestHeader(value = “xxxx”,required = false) String user 的方式获取请求头

    @ApiOperation(value = "特定用户的租户分页", notes = "特定用户的租户分页")
    @GetMapping(value = "/queryByUserName")
    public Response queryByUserName(/*@RequestHeader Map headers*/
                                    @RequestHeader(value = "user",required = false) String user,
                                    @RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize
                                   ) {

     
        log.info("------>拿到的请求头是:"+user);
        JSONObject jsonObject = JSONObject.parseObject(user);
        String userName= (String)jsonObject.get("user_name");
        // sun_13989882379
        log.debug(userName+ "");
       
        Page<TenantPO> pageInfo = tenantServiceFeign.selectByUserName(pageNum,pageSize,userName);
        return Response.ok(PageOut.build(pageInfo, TenantDto.class));
    }

可以利用下面的方式获取所有的请求头:

 @ApiOperation(value = "特定用户的租户分页", notes = "特定用户的租户分页")
    @GetMapping(value = "/queryByUserName")
    public Response queryByUserName(@RequestHeader Map<String, String> headers,
                                    @RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize
                                   ) {
       headers.forEach((key, value) -> {
            // 日志中输出所有请求头
            // Header 'user' = {"JWT_USER_ID_":1,"user_name":"sunj_13989882379","scope":["all"],"exp":1634643867,"JWT_USER_NAME_":"sunj_13989882379",
            // "jti":"e24ef65b-8302-41d3-91f3-2f92366d51fe","client_id":"clientapp"}
            log.debug(String.format("Header '%s' = %s", key, value));
        });
        
        Page<TenantPO> pageInfo = tenantServiceFeign.selectByUserName(pageNum,pageSize,userName);
        return Response.ok(PageOut.build(pageInfo, TenantDto.class));
    }

2、使用拦截器

如果有几十个接口那么都要使用注解写,过于累赘,可以使用拦截器进行开发,代码如下。

(1)声明 上下文

/**
 * 规定所有的Http头中必须携带Token 来验证用户身份,采用在拦截器用户名信息绑定到ThreadLocal,以供后续方法使用
 * 声明 上下文
 */
public class RequestHeaderContext {

    private static final ThreadLocal<RequestHeaderContext> REQUEST_HEADER_CONTEXT_THREAD_LOCAL=new ThreadLocal<>();
    private String userName;
   // private String token;

    public String getUserName() {
        return userName;
    }

    /*public String getToken() {
        return token;
    }*/

    public static RequestHeaderContext getInstance(){
        return REQUEST_HEADER_CONTEXT_THREAD_LOCAL.get();
    }

    public void setContext(RequestHeaderContext context){
        REQUEST_HEADER_CONTEXT_THREAD_LOCAL.set(context);
    }

    public static void clean(){
        REQUEST_HEADER_CONTEXT_THREAD_LOCAL.remove();
    }

    private RequestHeaderContext(RequestHeaderContextBuild requestHeaderContextBuild){
        this.userName=requestHeaderContextBuild.userName;
        // this.token=requestHeaderContextBuild.token;
        setContext(this);
    }

    public static class RequestHeaderContextBuild{
        private String userName;
        // private String token;

        public RequestHeaderContextBuild userName(String userName){
            this.userName=userName;
            return this;
        }

        /*public RequestHeaderContextBuild token(String token){
            this.token=token;
            return this;
        }*/
        public RequestHeaderContext bulid(){
            return new RequestHeaderContext(this);
        }
    }
}

(2)声明拦截器

/**
 * 声明拦截器
 */
@Slf4j
public class RequestHeaderContextInterceptor extends HandlerInterceptorAdapter {
    // private static final String HEAD_USER_NAME = "user_name";
    private static final String HEAD_TOKEN = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initHeaderContext(request);
        return super.preHandle(request, response, handler);
    }

    private void initHeaderContext(HttpServletRequest request){

        String userInfo = request.getHeader("user");
        log.info(">>>>>>>拦截到api相关请求头<<<<<<<<"+userInfo);

        JSONObject jsonObject = JSONObject.parseObject(userInfo);
        String user_name = (String) jsonObject.get("user_name");

        new RequestHeaderContext.RequestHeaderContextBuild()
                //.token(request.getHeader(HEAD_TOKEN))
                .userName(user_name)
                .bulid();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        RequestHeaderContext.clean();
        super.postHandle(request, response, handler, modelAndView);
    }
}

(3)绑定拦截器

/**
 * 绑定拦截器
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public HandlerInterceptor requestHeaderContextInterceptor() {
        return new RequestHeaderContextInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestHeaderContextInterceptor()).addPathPatterns("/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}

(4)使用

@ApiOperation(value = "特定用户的租户分页", notes = "特定用户的租户分页")
    @GetMapping(value = "/queryByUserName")
    public Response queryByUserName(
                                    @RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize
                                   ) {

        String userName = RequestHeaderContext.getInstance().getUserName();
        log.debug( "user_name ---> " + RequestHeaderContext.getInstance().getUserName());

        // 此租户的分页查询是查询所有的租户,而不是查询一个用户下关联的租户
        // 需要先根据用户名,筛选出相关的租户id,然后根据租户id得到租户的信息
        Page<TenantPO> pageInfo = tenantServiceFeign.selectByUserName(pageNum,pageSize,userName);
        return Response.ok(PageOut.build(pageInfo, TenantDto.class));
    }

你可能感兴趣的:(spring_全家桶,java,restful,spring,boot)