好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring MVC请求参数接收的全面总结教程

前提

在日常使用springmvc进行开发的时候,有可能遇到前端各种类型的 请求 参数 ,这里做一次相对全面的总结。springmvc中处理控制器参数的接口是handlermethodargumentresolver,此接口有众多子类,分别处理不同(注解类型)的参数,下面只列举几个子类:

requestparammethodargumentresolver:解析处理使用了@requestparam注解的参数、multipartfile类型参数和simple类型(如long、int)参数。 requestresponsebodymethodprocessor:解析处理@requestbody注解的参数。 pathvariablemapmethodargumentresolver:解析处理@pathvariable注解的参数。

实际上,一般在解析一个控制器的请求参数的时候,用到的是handlermethodargumentresolvercomposite,里面装载了所有启用的handlermethodargumentresolver子类。而handlermethodargumentresolver子类在解析参数的时候使用到httpmessageconverter(实际上也是一个列表,进行遍历匹配解析)子类进行匹配解析,常见的如mappingjackson2httpmessageconverter。而handlermethodargumentresolver子类到底依赖什么httpmessageconverter实例实际上是由请求头中的contenttype(在springmvc中统一命名为mediatype,见org.springframework.http.mediatype)决定的,因此我们在处理控制器的请求参数之前必须要明确外部请求的contenttype到底是什么。上面的逻辑可以直接看源码abstractmessageconvertermethodargumentresolver#readwithmessageconverters,思路是比较清晰的。在@requestmapping注解中,produces和consumes就是和请求或者响应的contenttype相关的:

consumes:指定处理请求的提交内容类型(contenttype),例如application/json, text/html,只有命中了才会接受该请求。 produces:指定返回的内容类型,仅当request请求头中的(accept)类型中包含该指定类型才返回,如果返回的是json数据一般使用application/json;charset=utf-8。

另外提一点,springmvc中默认使用jackson作为json的工具包,如果不是完全理解透整套源码的运作,一般不是十分建议修改默认使用的mappingjackson2httpmessageconverter(例如有些人喜欢使用fastjson,实现httpmessageconverter引入fastjson做转换器)。

springmvc请求参数接收

其实一般的表单或者json数据的请求都是相对简单的,一些复杂的处理主要包括url路径参数、文件上传、数组或者列表类型数据等。另外,关于参数类型中存在日期类型属性(例如java.util.date、java.sql.date、java.time.localdate、java.time.localdatetime),解析的时候一般需要自定义实现的逻辑实现string->日期类型的转换。其实道理很简单,日期相关的类型对于每个国家、每个时区甚至每个使用者来说认知都不一定相同。在演示一些例子主要用到下面的模特类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@data

public class user {

 

  private string name;

  private integer age;

  private list<contact> contacts;

}

 

@data

public class contact {

 

  private string name;

  private string phone;

}

表单参数

非对象类型单个参数接收:

这种是最常用的表单参数提交,contenttype指定为application/x-www-form-urlencoded,也就是会进行url编码。

对应的控制器如下:

?

1

2

3

4

5

6

7

@postmapping (value = "/post" )

public string post( @requestparam (name = "name" ) string name,

  @requestparam (name = "age" ) integer age) {

  string content = string.format( "name = %s,age = %d" , name, age);

  log.info(content);

  return content;

}

说实话,如果有毅力的话,所有的复杂参数的提交最终都可以转化为多个单参数接收,不过这样做会产生十分多冗余的代码,而且可维护性比较低。这种情况下,用到的参数处理器是requestparammapmethodargumentresolver。

对象类型参数接收:

我们接着写一个接口用于提交用户信息,用到的是上面提到的模特类,主要包括用户姓名、年龄和联系人信息列表,这个时候,我们目标的控制器最终编码如下:

?

1

2

3

4

5

@postmapping (value = "/user" )

public user saveuser(user user) {

  log.info(user.tostring());

  return user;

}

我们还是指定contenttype为application/x-www-form-urlencoded,接着我们需要构造请求参数:

因为没有使用注解,最终的参数处理器为servletmodelattributemethodprocessor,主要是把httpservletrequest中的表单参数封装到mutablepropertyvalues实例中,再通过参数类型实例化(通过构造反射创建user实例),反射匹配属性进行值的填充。另外,请求复杂参数里面的列表属性请求参数看起来比较奇葩,实际上和在.properties文件中添加最终映射到map类型的参数的写法是一致的。那么,能不能把整个请求参数塞在一个字段中提交呢?

直接这样做是不行的,因为实际提交的form表单,key是user,value实际上是一个字符串,缺少一个string->user类型的转换器,实际上requestparammethodargumentresolver依赖webconversionservice中converter列表进行参数转换:

解决办法还是有的,添加一个org.springframework.core.convert.converter.converter实现即可:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@component

public class stringuserconverter implements converter<string, user> {

 

  private static final objectmapper mapper = new objectmapper();

 

  @override

  public user convert(string source) {

  try {

  return mapper.readvalue(source, user. class );

  } catch (ioexception e) {

  throw new illegalargumentexception(e);

  }

  }

}

上面这种做法属于曲线救国的做法,不推荐使用在生产环境,但是如果有些第三方接口的对接无法避免这种参数,可以选择这种实现方式。

json参数

一般来说,直接post一个json字符串这种方式对于springmvc来说是比较友好的,只需要把contenttype设置为application/json,提交一个原始的json字符串即可:

后端控制器的代码也比较简单:

?

1

2

3

4

5

@postmapping (value = "/user-2" )

public user saveuser2( @requestbody user user) {

  log.info(user.tostring());

  return user;

}

因为使用了@requestbody注解,最终使用到的参数处理器为requestresponsebodymethodprocessor,实际上会用到mappingjackson2httpmessageconverter进行参数类型的转换,底层依赖到jackson相关的包。

url参数

url参数,或者叫请求路径参数是基于url模板获取到的参数,例如/user/{userid}是一个url模板(url模板中的参数占位符是{}),实际请求的url为/user/1,那么通过匹配实际请求的url和url模板就能提取到userid为1。在springmvc中,url模板中的路径参数叫做pathvariable,对应注解@pathvariable,对应的参数处理器为pathvariablemethodargumentresolver。注意一点是,@pathvariable的解析是按照value(name)属性进行匹配,和url参数的顺序是无关的。举个简单的例子:

后台的控制器如下:

?

1

2

3

4

5

6

7

@getmapping (value = "/user/{name}/{age}" )

public string finduser1( @pathvariable (value = "age" ) integer age,

  @pathvariable (value = "name" ) string name) {

  string content = string.format( "name = %s,age = %d" , name, age);

  log.info(content);

  return content;

}

这种用法被广泛使用于representational state transfer(rest)的软件架构风格,个人觉得这种风格是比较灵活和清晰的(从url和请求方法就能完全理解接口的意义和功能)。下面再介绍两种相对特殊的使用方式。

带条件的url参数

其实路径参数支持正则表达式,例如我们在使用/sex/{sex}接口的时候,要求sex必须是f(female)或者m(male),那么我们的url模板可以定义为/sex/{sex:m|f},代码如下:

?

1

2

3

4

5

@getmapping (value = "/sex/{sex:m|f}" )

public string finduser2( @pathvariable (value = "sex" ) string sex){

  log.info(sex);

  return sex;

}

只有/sex/f或者/sex/m的请求才会进入finduser2控制器方法,其他该路径前缀的请求都是非法的,会返回404状态码。这里仅仅是介绍了一个最简单的url参数正则表达式的使用方式,更强大的用法可以自行摸索。

@matrixvariable的使用

matrixvariable也是url参数的一种,对应注解@matrixvariable,不过它并不是url中的一个值(这里的值指定是两个"/"之间的部分),而是值的一部分,它通过";"进行分隔,通过"="进行k-v设置。说起来有点抽象,举个例子:假如我们需要打电话给一个名字为doge,性别是男,分组是码畜的程序员,get请求的url可以表示为:/call/doge;gender=male;group=programmer,我们设计的控制器方法如下:

?

1

2

3

4

5

6

7

8

@getmapping (value = "/call/{name}" )

public string find( @pathvariable (value = "name" ) string name,

  @matrixvariable (value = "gender" ) string gender,

  @matrixvariable (value = "group" ) string group) {

  string content = string.format( "name = %s,gender = %s,group = %s" , name, gender, group);

  log.info(content);

  return content;

}

当然,如果你按照上面的例子写好代码,尝试请求一下该接口发现是报错的:400 bad request - missing matrix variable 'gender' for method parameter of type string。这是因为@matrixvariable注解的使用是不安全的,在springmvc中默认是关闭对其支持。要开启对@matrixvariable的支持,需要设置requestmappinghandlermapping#setremovesemicoloncontent方法为false:

?

1

2

3

4

5

6

7

8

9

10

11

@configuration

public class custommvcconfiguration implements initializingbean {

 

  @autowired

  private requestmappinghandlermapping requestmappinghandlermapping;

 

  @override

  public void afterpropertiesset() throws exception {

  requestmappinghandlermapping.setremovesemicoloncontent( false );

  }

}

除非有很特殊的需要,否则不建议使用@matrixvariable。

文件上传

文件上传在使用postman模拟请求的时候需要选择form-data,post方式进行提交:

假设我们在d盘有一个图片文件叫doge.jpg,现在要通过本地服务接口把文件上传,控制器的代码如下:

?

1

2

3

4

5

6

7

@postmapping (value = "/file1" )

public string file1( @requestpart (name = "file1" ) multipartfile multipartfile) {

  string content = string.format( "name = %s,originname = %s,size = %d" ,

  multipartfile.getname(), multipartfile.getoriginalfilename(), multipartfile.getsize());

  log.info(content);

  return content;

}

控制台输出是:

?

1

name = file1,originname = doge.jpg,size = 68727

可能有点疑惑,参数是怎么来的,我们可以用fildder抓个包看下:

可知multipartfile实例的主要属性分别来自content-disposition、content-type和content-length,另外,inputstream用于读取请求体的最后部分(文件的字节序列)。参数处理器用到的是requestpartmethodargumentresolver(记住一点,使用了@requestpart和multipartfile一定是使用此参数处理器)。在其他情况下,使用@requestparam和multipartfile或者仅仅使用multipartfile(参数的名字必须和post表单中的content-disposition描述的name一致)也可以接收上传的文件数据,主要是通过requestparammethodargumentresolver进行解析处理的,它的功能比较强大,具体可以看其supportsparameter方法,这两种情况的控制器方法代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@postmapping (value = "/file2" )

public string file2(multipartfile file1) {

  string content = string.format( "name = %s,originname = %s,size = %d" ,

  file1.getname(), file1.getoriginalfilename(), file1.getsize());

  log.info(content);

  return content;

}

 

@postmapping (value = "/file3" )

public string file3( @requestparam (name = "file1" ) multipartfile multipartfile) {

  string content = string.format( "name = %s,originname = %s,size = %d" ,

  multipartfile.getname(), multipartfile.getoriginalfilename(), multipartfile.getsize());

  log.info(content);

  return content;

}

其他参数

其他参数主要包括请求头、cookie、model、map等相关参数,还有一些并不是很常用或者一些相对原生的属性值获取(例如httpservletrequest、httpservletresponse等)不做讨论。

请求头

请求头的值主要通过@requestheader注解的参数获取,参数处理器是requestheadermethodargumentresolver,需要在注解中指定请求头的key。简单实用如下:

控制器方法代码:

?

1

2

3

4

@postmapping (value = "/header" )

public string header( @requestheader (name = "content-type" ) string contenttype) {

  return contenttype;

}

cookie

cookie的值主要通过@cookievalue注解的参数获取,参数处理器为servletcookievaluemethodargumentresolver,需要在注解中指定cookie的key。控制器方法代码如下:

?

1

2

3

4

@postmapping (value = "/cookie" )

public string cookie( @cookievalue (name = "jsessionid" ) string sessionid) {

  return sessionid;

}

model类型参数

model类型参数的处理器是modelmethodprocessor,实际上处理此参数是直接返回modelandviewcontainer实例中的model(modelmap类型),因为要桥接不同的接口和类的功能,因此回调的实例是bindingawaremodelmap类型,此类型继承自modelmap同时实现了model接口。举个例子:

?

1

2

3

4

5

@getmapping (value = "/model" )

public string model(model model, modelmap modelmap) {

  log.info( "{}" , model == modelmap);

  return "success" ;

}

注意调用此接口,控制台输出info日志内容为:true。modelmap或者model中添加的属性项会附加到httprequestservlet中带到页面中进行渲染。

@modelattribute参数

@modelattribute注解处理的参数处理器为modelattributemethodprocessor,@modelattribute的功能源码的注释如下:

?

1

annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.

简单来说,就是通过key-value形式绑定方法参数或者方法返回值到model(map)中,区别下面三种情况:

1、@modelattribute使用在方法(返回值)上,方法没有返回值(void类型), model(map)参数需要自行设置。

2、@modelattribute使用在方法(返回值)上,方法有返回值(非void类型),返回值会添加到model(map)参数,key由@modelattribute的value指定,否则会使用返回值类型字符串(首写字母变为小写)。

3、@modelattribute使用在方法参数中。

在一个控制器(使用了@controller)中,如果存在一到多个使用了@modelattribute的方法,这些方法总是在进入控制器方法之前执行,并且执行顺序是由加载顺序决定的(具体的顺序是带参数的优先,并且按照方法首字母升序排序),举个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

@slf4j

@restcontroller

public class modelattributecontroller {

 

  @modelattribute

  public void before(model model) {

  log.info( "before.........." );

  model.addattribute( "before" , "beforevalue" );

  }

 

  @modelattribute (value = "beforearg" )

  public string beforearg() {

  log.info( "beforearg.........." );

  return "beforeargvalue" ;

  }

 

  @getmapping (value = "/modelattribute" )

  public string modelattribute(model model, @modelattribute (value = "beforearg" ) string beforearg) {

  log.info( "modelattribute.........." );

  log.info( "beforearg..........{}" , beforearg);

  log.info( "{}" , model);

  return "success" ;

  }

 

  @modelattribute

  public void after(model model) {

  log.info( "after.........." );

  model.addattribute( "after" , "aftervalue" );

  }

 

  @modelattribute (value = "afterarg" )

  public string afterarg() {

  log.info( "afterarg.........." );

  return "afterargvalue" ;

  }

}

调用此接口,控制台输出日志如下:

after..........
before..........
afterarg..........
beforearg..........
modelattribute..........
beforearg..........beforeargvalue
{after=aftervalue, before=beforevalue, afterarg=afterargvalue, beforearg=beforeargvalue}

可以印证排序规则和参数设置、获取。

errors或者bindingresult参数

errors其实是bindingresult的父接口,bindingresult主要用于回调jsr参数校验异常的属性项,如果jsr校验异常,一般会抛出methodargumentnotvalidexception异常,并且会返回400(bad request),见全局异常处理器defaulthandlerexceptionresolver。errors类型的参数处理器为errorsmethodargumentresolver。

举个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@postmapping (value = "/errors" )

public string errors( @requestbody @validated errorsmodel errors, bindingresult bindingresult) {

  if (bindingresult.haserrors()) {

  for (objecterror objecterror : bindingresult.getallerrors()) {

  log.warn( "name={},message={}" , objecterror.getobjectname(), objecterror.getdefaultmessage());

  }

  }

  return errors.tostring();

}

 

//errorsmodel

@data

@noargsconstructor

public class errorsmodel {

  @notnull (message = "id must not be null!" )

  private integer id;

  @notempty (message = "errors name must not be empty!" )

  private string name;

}

调用接口控制台warn日志如下:

name=errors,message=errors name must not be empty!

一般情况下,不建议用这种方式处理jsr校验异常的属性项,因为会涉及到大量的重复的硬编码工作,建议直接继承responseentityexceptionhandler,覆盖对应的方法。

@value参数

控制器方法的参数可以是@value注解修饰的参数,会从environment中装配和转换属性值到对应的参数中(也就是参数的来源并不是请求体),参数处理器为expressionvaluemethodargumentresolver。举个例子:

?

1

2

3

4

5

@getmapping (value = "/value" )

public string value( @value (value = "${spring.application.name}" ) string name) {

  log.info( "spring.application.name={}" , name);

  return name;

}

map类型参数

map类型参数的范围相对比较广,对应一系列的参数处理器,注意区别使用了上面提到的部分注解的map类型和完全不使用注解的map类型参数,两者的处理方式不相同。下面列举几个相对典型的map类型参数处理例子。

不使用任何注解的map<string,object>参数

这种情况下参数实际上直接回调modelandviewcontainer中的modelmap实例,参数处理器为mapmethodprocessor,往map参数中添加的属性将会带到页面中。

使用@requestparam注解的map<string,object>参数

这种情况下的参数处理器为requestparammapmethodargumentresolver,使用的请求方式需要指定contenttype为x-www-form-urlencoded,不能使用application/json的方式:

控制器代码为:

?

1

2

3

4

5

@postmapping (value = "/map" )

public string mapargs( @requestparam map<string, object> map) {

  log.info( "{}" , map);

  return map.tostring();

}

使用@requestheader注解的map<string,object>参数

这种情况下的参数处理器为requestheadermapmethodargumentresolver,作用是获取请求的所有请求头的key-value。

使用@pathvariable注解的map<string,object>参数

这种情况下的参数处理器为pathvariablemapmethodargumentresolver,作用是获取所有路径参数封装为key-value结构。

multipartfile集合-批量文件上传

批量文件上传的时候,我们一般需要接收一个multipartfile集合,可以有两种选择:

1、使用multiparthttpservletrequest参数,直接调用getfiles方法获取multipartfile列表。2、使用@requestparam注解修饰multipartfile列表,参数处理器是requestparammethodargumentresolver,其实就是第一种的封装而已。

控制器方法代码如下:

?

1

2

3

4

5

@postmapping (value = "/parts" )

public string partargs( @requestparam (name = "file" ) list<multipartfile> parts) {

  log.info( "{}" , parts);

  return parts.tostring();

}

日期类型参数处理

日期处理个人认为是请求参数处理中最复杂的,因为一般日期处理的逻辑不是通用的,过多的定制化处理导致很难有一个统一的标准处理逻辑去处理和转换日期类型的参数。不过,这里介绍几个通用的方法,以应对各种奇葩的日期格式。下面介绍的例子中全部使用jdk8中引入的日期时间api,围绕java.util.date为核心的日期时间api的使用方式类同。

一、统一以字符串形式接收

这种是最原始但是最奏效的方式,统一以字符串形式接收,然后自行处理类型转换,下面给个小例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

@postmapping (value = "/date1" )

public string date1( @requestbody userdto userdto) {

  userentity userentity = new userentity();

  userentity.setuserid(userdto.getuserid());

  userentity.setbirthdaytime(localdatetime.parse(userdto.getbirthdaytime(), formatter));

  userentity.setgraduationtime(localdatetime.parse(userdto.getgraduationtime(), formatter));

  log.info(userentity.tostring());

  return "success" ;

}

 

@data

public class userdto {

 

  private string userid;

  private string birthdaytime;

  private string graduationtime;

}

 

@data

public class userentity {

 

  private string userid;

  private localdatetime birthdaytime;

  private localdatetime graduationtime;

}

二、使用注解@datetimeformat或者@jsonformat

@datetimeformat注解配合@requestbody的参数使用的时候,会发现抛出invalidformatexception异常,提示转换失败,这是因为在处理此注解的时候,只支持form提交(contenttype为x-www-form-urlencoded),例子如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

@data

public class userdto2 {

 

  private string userid;

  @datetimeformat (pattern = "yyyy-mm-dd hh:mm:ss" )

  private localdatetime birthdaytime;

  @datetimeformat (pattern = "yyyy-mm-dd hh:mm:ss" )

  private localdatetime graduationtime;

}

 

 

@postmapping (value = "/date2" )

public string date2(userdto2 userdto2) {

  log.info(userdto2.tostring());

  return "success" ;

}

 

//或者像下面这样

@postmapping (value = "/date2" )

public string date2( @requestparam ( "name" = "userid" )string userid,

   @requestparam ( "name" = "birthdaytime" ) @datetimeformat (pattern = "yyyy-mm-dd hh:mm:ss" ) localdatetime birthdaytime,

   @requestparam ( "name" = "graduationtime" ) @datetimeformat (pattern = "yyyy-mm-dd hh:mm:ss" ) localdatetime graduationtime) {

  return "success" ;

}

而@jsonformat注解可使用在form或者json请求参数的场景,因此更推荐使用@jsonformat注解,不过注意需要指定时区(timezone属性,例如在中国是东八区"gmt+8"),否则有可能导致出现"时差",举个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@postmapping (value = "/date2" )

public string date2( @requestbody userdto2 userdto2) {

  log.info(userdto2.tostring());

  return "success" ;

}

 

@data

public class userdto2 {

 

  private string userid;

  @jsonformat (pattern = "yyyy-mm-dd hh:mm:ss" , timezone = "gmt+8" )

  private localdatetime birthdaytime;

  @jsonformat (pattern = "yyyy-mm-dd hh:mm:ss" , timezone = "gmt+8" )

  private localdatetime graduationtime;

}

三、jackson序列化和反序列化定制

因为springmvc默认使用jackson处理@requestbody的参数转换,因此可以通过定制序列化器和反序列化器来实现日期类型的转换,这样我们就可以使用application/json的形式提交请求参数。这里的例子是转换请求json参数中的字符串为localdatetime类型,属于json反序列化,因此需要定制反序列化器:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

@postmapping (value = "/date3" )

public string date3( @requestbody userdto3 userdto3) {

  log.info(userdto3.tostring());

  return "success" ;

}

 

@data

public class userdto3 {

 

  private string userid;

  @jsondeserialize (using = customlocaldatetimedeserializer. class )

  private localdatetime birthdaytime;

  @jsondeserialize (using = customlocaldatetimedeserializer. class )

  private localdatetime graduationtime;

}

 

public class customlocaldatetimedeserializer extends localdatetimedeserializer {

 

  public customlocaldatetimedeserializer() {

  super (datetimeformatter.ofpattern( "yyyy-mm-dd hh:mm:ss" ));

  }

}

四、最佳实践

前面三种方式都存在硬编码等问题,其实最佳实践是直接修改mappingjackson2httpmessageconverter中的objectmapper对于日期类型处理默认的序列化器和反序列化器,这样就能全局生效,不需要再使用其他注解或者定制序列化方案(当然,有些时候需要特殊处理定制),或者说,在需要特殊处理的场景才使用其他注解或者定制序列化方案。使用钩子接口jackson2objectmapperbuildercustomizer可以实现objectmapper的属性定制:

?

1

2

3

4

5

6

7

8

9

@bean

public jackson2objectmapperbuildercustomizer jackson2objectmapperbuildercustomizer(){

  return customizer->{

  customizer.serializerbytype(localdatetime. class , new localdatetimeserializer(

  datetimeformatter.ofpattern( "yyyy-mm-dd hh:mm:ss" )));

  customizer.deserializerbytype(localdatetime. class , new localdatetimedeserializer(

  datetimeformatter.ofpattern( "yyyy-mm-dd hh:mm:ss" )));

  };

}

这样就能定制化mappingjackson2httpmessageconverter中持有的objectmapper,上面的localdatetime序列化和反序列化器对全局生效。

请求url匹配

前面基本介绍完了主流的请求参数处理,其实springmvc中还会按照url的模式进行匹配,使用的是ant路径风格,处理工具类为org.springframework.util.antpathmatcher,从此类的注释来看,匹配规则主要包括下面四点:

1、?匹配1个字符。

2、*匹配0个或者多个字符。

3、**匹配路径中0个或者多个目录。

4、{spring:[a-z]+}将正则表达式[a-z]+匹配到的值,赋值给名为spring的路径变量。

举些例子:

?形式的url:

?

1

2

3

4

5

6

7

8

9

10

@getmapping (value = "/pattern?" )

public string pattern() {

  return "success" ;

}

 

/pattern 404 not found

/patternd 200 ok

/patterndd 404 not found

/pattern/ 404 not found

/patternd/s 404 not found

*形式的url:

?

1

2

3

4

5

6

7

8

9

@getmapping (value = "/pattern*" )

public string pattern() {

  return "success" ;

}

 

/pattern 200 ok

/pattern/ 200 ok

/patternd 200 ok

/pattern/a 404 not found

**形式的url:

?

1

2

3

4

5

6

7

8

@getmapping (value = "/pattern/**/p" )

public string pattern() {

  return "success" ;

}

 

/pattern/p 200 ok

/pattern/x/p 200 ok

/pattern/x/y/p 200 ok

{spring:[a-z]+}形式的url:

?

1

2

3

4

5

6

7

8

9

10

@getmapping (value = "/pattern/{key:[a-c]+}" )

public string pattern( @pathvariable (name = "key" ) string key) {

  return "success" ;

}

 

/pattern/a 200 ok

/pattern/ab 200 ok

/pattern/abc 200 ok

/pattern 404 not found

/pattern/abcd 404 not found

上面的四种url模式可以组合使用,千变万化。

url匹配还遵循精确匹配原则,也就是存在两个模式对同一个url都能够匹配成功,则选取最精确的url匹配,进入对应的控制器方法,举个例子:

?

1

2

3

4

5

6

7

8

9

@getmapping (value = "/pattern/**/p" )

public string pattern1() {

  return "success" ;

}

 

@getmapping (value = "/pattern/p" )

public string pattern2() {

  return "success" ;

}

上面两个控制器,如果请求url为/pattern/p,最终进入的方法为pattern2。

最后,org.springframework.util.antpathmatcher作为一个工具类,可以单独使用,不仅仅可以用于匹配url,也可以用于匹配系统文件路径,不过需要使用其带参数构造改变内部的pathseparator变量,例如:

?

1

antpathmatcher antpathmatcher = new antpathmatcher(file.separator);

小结

笔者在前一段时间曾经花大量时间梳理和分析过spring、springmvc的源码,但是后面一段很长的时间需要进行业务开发,对架构方面的东西有点生疏了,毕竟东西不用就会生疏,这个是常理。这篇文章基于一些springmvc的源码经验总结了请求参数的处理相关的一些知识,希望帮到自己和大家。

参考资料:

spring-boot-web-starter:2.0.3.release源码。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://www.cnblogs.com/throwable/p/9434436.html

查看更多关于Spring MVC请求参数接收的全面总结教程的详细内容...

  阅读:57次