通过HttpServletRequest重写+filter 添加header

问题说明

需要做的事情比较简单,就是通过filter 重写httpservletrequest ,同时给予request 添加header
主要是通过HttpServletRequestWrapper 进行处理,代码写死了,只是一个简单的演示。

自定义HttpServletRequest(实现HttpServletRequestWrapper)

package com.example.demo;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

final class MutableHttpServletRequest extends HttpServletRequestWrapper {
    private final Map<String, String> customHeaders;

    public MutableHttpServletRequest(HttpServletRequest request){
        super(request);
        this.customHeaders = new HashMap<String, String>();
    }

    public void putHeader(String name, String value){
        this.customHeaders.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        if (name=="userid") {
            return "dalong";
        }
        return "demo";
    }

    public Map<String, String> getCustomHeaders() {
        return customHeaders;
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        if (null != name && name.equals("userid")) {
            return new Enumeration<String>() {
                private boolean hasGetted = false;

                @Override
                public boolean hasMoreElements() {
                    return !hasGetted;
                }

                @Override
                public String nextElement() {
                    if (hasGetted) {
                        throw new NoSuchElementException();
                    } else {
                        hasGetted = true;
                        return "dalong";
                    }
                }
            };
        }
        return super.getHeaders(name);

    }
}

filter

调用自定义HttpServletRequestWrapper 实现header 添加

package com.example.demo;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "tokenfilter")
public class UserIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        MutableHttpServletRequest newrequest = new MutableHttpServletRequest(request);
        System.out.printf("filter running");
        filterChain.doFilter(newrequest,response);
    }
}

scan

添加scan 自动注入filter

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
 }

}

service

rest api 测试

package com.example.demo;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
public class UserService {
    @RequestMapping(value = "/user",method= RequestMethod.GET)
    public Object Userinfo(HttpServletRequest request,@RequestHeader String userid){
       // User user =new User(request.getHeader("userid"),222);
        User user =new User(userid,222);
        return user;
    }
}

user entity

用户实体,用来测试的

package com.example.demo;

public class User {

    private String username;
    private int age;

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public User() {

    }
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

applicaiton 入口

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

测试效果

curl -i http://localhost:8080/user
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 11 May 2019 15:09:19 GMT
{"username":"dalong","age":222}%      

说明

getHeaders 也是需要实现的,不然基于注解的@RequestHeader 不生效

参考资料

http://wilddiary.com/adding-custom-headers-java-httpservletrequest/
https://github.com/rongfengliang/HttpServletRequst-Rewrite-Demo

posted on 2019-05-11 23:31  荣锋亮  阅读(2355)  评论(0编辑  收藏  举报

导航