欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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;

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