当前位置 : 主页 > 编程语言 > java >

SpringBoot 请求参数忽略大小写的实例

来源:互联网 收集:自由互联 发布时间:2021-04-03
我就废话不多说了,大家还是直接看代码吧~ import java.io.IOException;import java.util.Collections;import java.util.Enumeration;import java.util.Map; import javax.servlet.FilterChain;import javax.servlet.ServletException;imp

我就废话不多说了,大家还是直接看代码吧~

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":"121607691@qq.com"
}

springboot 接到的DOI和PMID 为null,头字母改为小写后正常。

原因及解决

是spring 使用@requestbody 接收时遵循驼峰命名规则,如果希望接收非驼峰的参数可以在对映的属性上添加注解

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。

网友评论