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

时间:2021-05-20

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

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;

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章