通过包装request,实际调用的是包装之后的request对象
1.主类WebDemoApplication
@SpringBootApplication
@ServletComponentScan
public class WebDemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebDemoApplication.class, args);
}
}
2.ControllerFileter
@WebFilter(urlPatterns = "/*")
public class ControllerFileter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(new TokenRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}
}
3.TokenRequestWrapper
public class TokenRequestWrapper extends HttpServletRequestWrapper {
TokenRequestWrapper(HttpServletRequest request) {
super(request);
}
/**
* 修改此方法主要是因为当RequestMapper中的参数为pojo类型时,
* 会通过此方法获取所有的请求参数并进行遍历,对pojo属性赋值
* @return
*/
@Override
public Enumeration<String> getParameterNames() {
Enumeration<String> enumeration = super.getParameterNames();
ArrayList<String> list = Collections.list(enumeration);
//当有token字段时动态的添加uid字段
if (list.contains("token")){
list.add("uid");
return Collections.enumeration(list);
}else {
return super.getParameterNames();
}
}
@Override
public String[] getParameterValues(String name) {
if ("uid".equals(name)){
return new String[]{"1","2","3"};
}
return super.getParameterValues(name);
}
}
4.User
@Data
public class User {
private String uid;
private String name;
}
5.TestController
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
HttpServletRequest httpServletRequest;
@GetMapping("/param")
public Object param(String uid,String name){
return uid;
}
@GetMapping("/bean")
private Object gets(User user){
return user;
}
}
6.接口
/test/param?token=213&name=231
/test/bean?token=213&name=231
以下内容待研究当时怎么写的
=========================================================
public class MyRequestWrapper extends HttpServletRequestWrapper {
public MyRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
// 设置参数返回逻辑
System.out.println(super.getParameter(name));
return "yangshisheng";
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(new MyRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}
之后controller中使用的是包装后的request对象.
===============================================================