springboot filter获取不到post请求参数
时间: 2023-05-08 15:58:42 浏览: 145
springboot中不能获取post请求参数的解决方法
Spring Boot中的Filter是一种拦截所有请求的方式,无论是GET请求还是POST请求都会被Filter拦截到。但是有时候会遇到Filter获取不到POST请求参数的情况,这时候需要检查一下请求头中的Content-Type是否是application/x-www-form-urlencoded。
如果Content-Type是application/x-www-form-urlencoded,则需要通过HttpServletRequest.getParameter()方法来获取请求参数。例如:
``` java
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 获取请求参数
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
...
// 继续处理请求
chain.doFilter(request, response);
}
}
```
如果Content-Type是application/json,则需要通过读取请求体来获取请求参数。例如:
``` java
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 获取请求体
BufferedReader reader = request.getReader();
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// 解析JSON参数
JSONObject json = JSONObject.parseObject(sb.toString());
String param1 = json.getString("param1");
String param2 = json.getString("param2");
...
// 继续处理请求
chain.doFilter(request, response);
}
}
```
总之,要根据请求头中的Content-Type来确定获取POST请求参数的方法,否则会导致获取不到参数的情况。
阅读全文