在 web 开发中,经常会遇到请求入参、出参日志记录处理, 这时间如果不能规范化日志打印极有可能会踩坑。
比如在对 request 对象做 JSON 序列化时,在一些情况下就会报"Multipart request not initialized",
经过查看源码发现这是埋在底层的坑
以下做反向分析:
报错点,见 62 行,向上追溯到 41 行 getFileMap(), 此处会向下调用,一直到异常点
原因:AbstractMultipartHttpServletRequest 设计之初应该是解决文件上传问题,但是后来被扩展到 multipart Params 传输,在使用时如果有用到,在 JSON 序列化时文件为空就会报上述错误
警示:研发过程中在处理日志等序列化时要清楚的知道序列化对象的信息、大小、必要度,尽可能对自己真正需要的信息做日志
public abstract class AbstractMultipartHttpServletRequest extends HttpServletRequestWrapper implements MultipartHttpServletRequest {
private MultiValueMap<String, MultipartFile> multipartFiles;
protected AbstractMultipartHttpServletRequest(HttpServletRequest request) {
super(request);
}
public HttpServletRequest getRequest() {
return (HttpServletRequest)super.getRequest();
}
public HttpMethod getRequestMethod() {
return HttpMethod.valueOf(this.getRequest().getMethod());
}
public HttpHeaders getRequestHeaders() {
HttpHeaders headers = new HttpHeaders();
Enumeration<String> headerNames = this.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
headers.put(headerName, Collections.list(this.getHeaders(headerName)));
}
return headers;
}
public Iterator<String> getFileNames() {
return this.getMultipartFiles().keySet().iterator();
}
public MultipartFile getFile(String name) {
return (MultipartFile)this.getMultipartFiles().getFirst(name);
}
public List<MultipartFile> getFiles(String name) {
List<MultipartFile> multipartFiles = (List)this.getMultipartFiles().get(name);
return multipartFiles != null ? multipartFiles : Collections.emptyList();
}
public Map<String, MultipartFile> getFileMap() {
return this.getMultipartFiles().toSingleValueMap();
}
public MultiValueMap<String, MultipartFile> getMultiFileMap() {
return this.getMultipartFiles();
}
protected final void setMultipartFiles(MultiValueMap<String, MultipartFile> multipartFiles) {
this.multipartFiles = new LinkedMultiValueMap(Collections.unmodifiableMap(multipartFiles));
}
protected MultiValueMap<String, MultipartFile> getMultipartFiles() {
if (this.multipartFiles == null) {
this.initializeMultipart();
}
return this.multipartFiles;
}
protected void initializeMultipart() {
throw new IllegalStateException("Multipart request not initialized");
}
}
复制代码
评论