Springboot 使用【过滤器】实现在请求到达 Controller 之前修改请求体参数和在结果返回之前修改响应体
在Spring Boot中,你可以通过实现Filter
接口来创建一个自定义的过滤器,并在过滤器中修改请求体参数。以下是一个简单的例子:
- 创建一个过滤器类:
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.util.Enumeration;
@Component
public class ModifyRequestFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
ModifyableHttpServletRequestWrapper requestWrapper = new ModifyableHttpServletRequestWrapper(
httpServletRequest);
// 在这里修改请求体参数
requestWrapper.setParameter("paramName", "newValue");
chain.doFilter(requestWrapper, response);
}
}
private static class ModifyableHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public ModifyableHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = request.getReader();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
body = stringBuilder.toString();
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
return new ServletInputStream() {
@Override
public boolean isFinished() {
r
评论已关闭