请求方式:POST
数据格式:JSON
代码部分:Filter
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SfqIdFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 读取请求体
String originBody = getRequestBody(httpServletRequest);
String modifiedBody = handleSfqId(originBody);
// 包装请求
HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpServletRequest) {
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(modifiedBody.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
@Override
public boolean isFinished() {
return true;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
};
chain.doFilter(requestWrapper, response);
} else {
chain.doFilter(request, response);
}
}
private String getRequestBody(HttpServletRequest request){
StringBuffer stringBuilder = new StringBuffer("");
byte[] bytes = new byte[1024];
int len = 0;
try (InputStream inputStream = request.getInputStream()){
if (inputStream != null) {
while ((len = inputStream.read(bytes)) != -1) {
stringBuilder.append(new String(bytes, 0, len, "utf-8"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stringBuilder.toString();
}
/**
* 没有判断requestBody是否json格式
* */
private String handleSfqId(String requestBody) {
if (StringUtils.isEmpty(requestBody)){
return requestBody;
}
try {
JSONObject jsonBody = JSONObject.parseObject(requestBody);
Integer sfqId = jsonBody.getInteger("sfqId");
if (sfqId == null){
jsonBody.put("sfqId", "333");
}
return jsonBody.toJSONString();
} catch (Exception e) {
//解析失败,非json格式
e.printStackTrace();
}
return requestBody;
}
}
配置
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<SfqIdFilter> myFilter() {
FilterRegistrationBean<SfqIdFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new SfqIdFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(1);
return registrationBean;
}