SpringBoot 请求参数忽略大小写的实例
我就废话不多说了,大家还是直接看代码吧~
importjava.io.IOException; importjava.util.Collections; importjava.util.Enumeration; importjava.util.Map; importjavax.servlet.FilterChain; importjavax.servlet.ServletException; importjavax.servlet.annotation.WebFilter; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletRequestWrapper; importjavax.servlet.http.HttpServletResponse; importorg.springframework.core.annotation.Order; importorg.springframework.util.LinkedCaseInsensitiveMap; importorg.springframework.web.filter.OncePerRequestFilter; @Order(1) //重点 @WebFilter(filterName="caseInsensitiveFilter",urlPatterns="/*") publicclassCaseInsensitiveRequestParameterNameFilterextendsOncePerRequestFilter{ publicCaseInsensitiveRequestParameterNameFilter(){ System.out.println("CaseInsensitiveRequestParameterNameFilter.CaseInsensitiveRequestParameterNameFilter()"); } @Override protectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainfilterChain) throwsServletException,IOException{ filterChain.doFilter(newCaseInsensitiveParameterNameHttpServletRequest(request),response); } publicstaticclassCaseInsensitiveParameterNameHttpServletRequestextendsHttpServletRequestWrapper{ privatefinalLinkedCaseInsensitiveMapmap=newLinkedCaseInsensitiveMap<>(); publicCaseInsensitiveParameterNameHttpServletRequest(HttpServletRequestrequest){ super(request); map.putAll(request.getParameterMap()); } @Override publicStringgetParameter(Stringname){ String[]array=this.map.get(name); if(array!=null&&array.length>0) returnarray[0]; returnnull; } @Override publicMap getParameterMap(){ returnCollections.unmodifiableMap(this.map); } @Override publicEnumeration getParameterNames(){ returnCollections.enumeration(this.map.keySet()); } @Override publicString[]getParameterValues(Stringname){ returnthis.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") privateStringDOI;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。