前提
在日常使用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