1. 程式人生 > >Spring Servlet Web 5.1.3 常用過濾器 : FormContentFilter

Spring Servlet Web 5.1.3 常用過濾器 : FormContentFilter

概述

該過濾器針對DELETE,PUTPATCH這三種HTTP method分析其FORM表單引數,將其暴露為Servlet請求引數。

預設情況下,Servlet規範僅針對HTTP POST做這樣的要求。

該過濾器繼承自OncePerRequestFilter,也就是說,它在整個請求處理過程中最多隻會被應用一次。

Springboot 提供了一個OrderedFormContentFilter繼承自FormContentFilter應用在基於SpringbootServlet Web應用中。OrderedFormContentFilterFormContentFilter

的功能上增加了介面OrderedFilter定義的過濾器順序,並且預設使用優先順序(-9900)。在整個Servlet過濾器鏈中,過濾器的順序數字越小,表示越先被呼叫。

原始碼分析

package org.springframework.web.filter;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.
http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpInputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; public class FormContentFilter extends OncePerRequestFilter { // 該過濾器僅針對如下三種HTTP method生效 private static final List<String> HTTP_METHODS = Arrays.asList("PUT", "PATCH", "DELETE"); private FormHttpMessageConverter formConverter = new AllEncompassingFormHttpMessageConverter(); /** * Set the converter to use for parsing form content. * 設定分析表單內容的轉換器,預設使用的是一個 AllEncompassingFormHttpMessageConverter * >By default this is an instance of AllEncompassingFormHttpMessageConverter. */ public void setFormConverter(FormHttpMessageConverter converter) { Assert.notNull(converter, "FormHttpMessageConverter is required"); this.formConverter = converter; } /** * The default character set to use for reading form data. * 設定表單內容分析時使用的字符集 * 該方法是 getFormConverter.setCharset(charset) 的快捷方法 */ public void setCharset(Charset charset) { this.formConverter.setCharset(charset); } @Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 分析表單內容獲取引數 params MultiValueMap<String, String> params = parseIfNecessary(request); if (!CollectionUtils.isEmpty(params)) { // 如果 params 不為空,則封裝請求為一個FormContentRequestWrapper然後繼續過濾器鏈的呼叫 filterChain.doFilter(new FormContentRequestWrapper(request, params), response); } else { // 如果 params 為空,使用原來的請求繼續過濾器鏈的呼叫 filterChain.doFilter(request, response); } } // 分析表單內容獲取引數 @Nullable private MultiValueMap<String, String> parseIfNecessary(HttpServletRequest request) throws IOException { // 必須是 : PUT, DELETE , PATCH // 並且必須是 : application/x-www-form-urlencoded if (!shouldParse(request)) { return null; } // 獲取請求主體流,分析其中的引數為MultiValueMap<String, String>並返回 HttpInputMessage inputMessage = new ServletServerHttpRequest(request) { @Override public InputStream getBody() throws IOException { return request.getInputStream(); } }; return this.formConverter.read(null, inputMessage); } private boolean shouldParse(HttpServletRequest request) { // 僅僅支援 PUT, DELETE , PATCH if (!HTTP_METHODS.contains(request.getMethod())) { return false; } // 僅僅支援 application/x-www-form-urlencoded try { MediaType mediaType = MediaType.parseMediaType(request.getContentType()); return MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType); } catch (IllegalArgumentException ex) { return false; } } // 封裝請求和指定的引數,讓指定的引數呈現為被封裝請求的引數 private static class FormContentRequestWrapper extends HttpServletRequestWrapper { private MultiValueMap<String, String> formParams; public FormContentRequestWrapper(HttpServletRequest request, MultiValueMap<String, String> params) { super(request); this.formParams = params; } @Override @Nullable public String getParameter(String name) { // 注意,這裡還是優先使用request的queryString引數,只是queryString不存在時才從formParams中獲取 String queryStringValue = super.getParameter(name); String formValue = this.formParams.getFirst(name); return (queryStringValue != null ? queryStringValue : formValue); } @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> result = new LinkedHashMap<>(); Enumeration<String> names = getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); result.put(name, getParameterValues(name)); } return result; } @Override public Enumeration<String> getParameterNames() { Set<String> names = new LinkedHashSet<>(); names.addAll(Collections.list(super.getParameterNames())); names.addAll(this.formParams.keySet()); return Collections.enumeration(names); } // 獲取指定屬性的所有值,會合並queryString中的值和外部指定的formParams中的值到一起然後返回 @Override @Nullable public String[] getParameterValues(String name) { String[] parameterValues = super.getParameterValues(name); List<String> formParam = this.formParams.get(name); if (formParam == null) { return parameterValues; } if (parameterValues == null || getQueryString() == null) { return StringUtils.toStringArray(formParam); } else { List<String> result = new ArrayList<>(parameterValues.length + formParam.size()); result.addAll(Arrays.asList(parameterValues)); result.addAll(formParam); return StringUtils.toStringArray(result); } } } }