SpringBoot 请求参数忽略大小写的实例
程序员文章站
2022-03-20 22:54:46
我就废话不多说了,大家还是直接看代码吧~import java.io.ioexception;import java.util.collections;import java.util.enumera...
我就废话不多说了,大家还是直接看代码吧~
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;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
推荐阅读
-
postman测试post请求参数为json类型的实例讲解
-
SpringBoot使用Aspect切面拦截打印请求参数的示例代码
-
python requests 库请求带有文件参数的接口实例
-
解决Springboot get请求是参数过长的情况
-
SpringBoot @Validated注解实现参数分组校验的方法实例
-
使用Springboot注入带参数的构造函数实例
-
GO接收GET/POST参数及发送GET/POST请求的实例详解
-
springboot的restTemplate发送参数为json的post请求
-
SpringBoot RestTemplate GET POST请求的实例讲解
-
SpringBoot 请求参数忽略大小写的实例