SpringBoot 請求參數忽略大小寫的實例

我就廢話不多說瞭,大傢還是直接看代碼吧~

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map; 
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse; 
import org.springframework.core.annotation.Order;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.filter.OncePerRequestFilter;
 
@Order(1)
//重點
@WebFilter(filterName = "caseInsensitiveFilter", urlPatterns = "/*")
public class CaseInsensitiveRequestParameterNameFilter extends OncePerRequestFilter {
 
	public CaseInsensitiveRequestParameterNameFilter() {
		System.out.println("CaseInsensitiveRequestParameterNameFilter.CaseInsensitiveRequestParameterNameFilter()");
	}
	
 @Override
 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
  throws ServletException, IOException {
 filterChain.doFilter(new CaseInsensitiveParameterNameHttpServletRequest(request), response);
 }
 
 public static class CaseInsensitiveParameterNameHttpServletRequest extends HttpServletRequestWrapper {
 private final LinkedCaseInsensitiveMap<String[]> map = new LinkedCaseInsensitiveMap<>();
 
 public CaseInsensitiveParameterNameHttpServletRequest(HttpServletRequest request) {
  super(request);
  map.putAll(request.getParameterMap());
 }
 
 @Override
 public String getParameter(String name) {
 
  String[] array = this.map.get(name);
  if (array != null && array.length > 0)
  return array[0];
  return null;
 }
 
 @Override
 public Map<String, String[]> getParameterMap() {
  return Collections.unmodifiableMap(this.map);
 }
 
 @Override
 public Enumeration<String> getParameterNames() {
  return Collections.enumeration(this.map.keySet());
 }
 
 @Override
 public String[] getParameterValues(String name) {
  return this.map.get(name);
 }
 
 }
 
}

並在啟動類上加入@ServletComponentScan註解

補充:springboot 接受大寫參數時,接收值為空的解決

入參:

{
 "title":"文章標題1",
 "content":"文章內容22222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222",
 "DOI":"123",
 "PMID":"1234",
 "email":"[email protected]"
}

springboot 接到的DOI和PMID 為null,頭字母改為小寫後正常。

原因及解決

是spring 使用@requestbody 接收時遵循駝峰命名規則,如果希望接收非駝峰的參數可以在對映的屬性上添加註解

@JsonProperty(value = "DOI")
private String DOI;

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。