詳解SpringMVC常用注解功能及屬性
1.@RequestMapping注解
1.1@RequestMapping注解的功能
從注解名稱上我們可以看到,@RequestMapping注解的作用就是將請求和處理請求的控制器方法關(guān)聯(lián)起來,建立映射關(guān)系。
SpringMVC 接收到指定的請求,就會來找到在映射關(guān)系中對應(yīng)的控制器方法來處理這個請求。
1.2@RequestMapping注解的位置
@RequestMapping標識一個類:設(shè)置映射請求的請求路徑的初始信息
@RequestMapping標識一個方法:設(shè)置映射請求請求路徑的具體信息
@Controller @RequestMapping("/test") public class RequestMappingController { //此時請求映射所映射的請求的請求路徑為:/test/testRequestMapping @RequestMapping("/testRequestMapping") public String testRequestMapping(){ return "success"; } }
1.3@RequestMapping注解的value屬性
@RequestMapping注解的value屬性通過請求的請求地址匹配請求映射
@RequestMapping注解的value屬性是一個字符串類型的數(shù)組,表示該請求映射能夠匹配多個請求地址所對應(yīng)的請求
@RequestMapping注解的value屬性必須設(shè)置,至少通過請求地址匹配請求映射
<a th:href="@{/testRequestMapping}" rel="external nofollow" >測試@RequestMapping的value屬性-->/testRequestMapping</a><br> <a th:href="@{/test}" rel="external nofollow" rel="external nofollow" >測試@RequestMapping的value屬性-->/test</a><br>
@RequestMapping( value = {"/testRequestMapping", "/test"} ) public String testRequestMapping(){ return "success"; }
1.4@RequestMapping注解的method屬性
@RequestMapping注解的method屬性通過請求的請求方式(get或post)匹配請求映射
@RequestMapping注解的method屬性是一個RequestMethod類型的數(shù)組,表示該請求映射能夠匹配多種請求方式的請求
若當前請求的請求地址滿足請求映射的value屬性,但是請求方式不滿足method屬性,則瀏覽器報錯
405:Request method 'POST' not supported
<a th:href="@{/test}" rel="external nofollow" rel="external nofollow" >測試@RequestMapping的value屬性-->/test</a><br> <form th:action="@{/test}" method="post"> <input type="submit"> </form>
@RequestMapping( value = {"/testRequestMapping", "/test"}, method = {RequestMethod.GET, RequestMethod.POST} ) public String testRequestMapping(){ return "success"; }
注意:
(1)對于處理指定請求方式的控制器方法,SpringMVC
中提供了@RequestMapping
的派生注解:
處理get
請求的映射–>@GetMapping
處理post
請求的映射–>@PostMapping
處理put
請求的映射–>@PutMapping
處理delete
請求的映射–>@DeleteMapping
(2)常用的請求方式有get
,post
,put
,delete
但是目前瀏覽器只支持get和post,若在form表單提交時,為method設(shè)置了其他請求方式的字符串(put或delete),則按照默認的請求方式get處理。
若要發(fā)送put和delete請求,則需要通過spring提供的過濾器HiddenHttpMethodFilter
。
1.5@RequestMapping注解的params屬性(了解)
@RequestMapping注解的params屬性通過請求的請求參數(shù)匹配請求映射
@RequestMapping注解的params屬性是一個字符串類型的數(shù)組,可以通過四種表達式設(shè)置請求參數(shù)和請求映射的匹配關(guān)系
"param"
:要求請求映射所匹配的請求必須攜帶param請求參數(shù)
"!param"
:要求請求映射所匹配的請求必須不能攜帶param請求參數(shù)
"param=value"
:要求請求映射所匹配的請求必須攜帶param請求參數(shù)且param=value
"param!=value"
:要求請求映射所匹配的請求必須攜帶param請求參數(shù)但是param!=value
<a th:href="@{/test(username='admin',password=123456)" rel="external nofollow" >測試@RequestMapping的params屬性-->/test</a><br>
@RequestMapping( value = {"/testRequestMapping", "/test"} ,method = {RequestMethod.GET, RequestMethod.POST} ,params = {"username","password!=123456"} ) public String testRequestMapping(){ return "success"; }
注意:
若當前請求滿足@RequestMapping注解的value和method屬性,但是不滿足params屬性,此時頁面會報錯
400:Parameter conditions "username, password!=123456" not met for actual request parameters: username={admin}, password={123456}
1.6@RequestMapping注解的headers屬性(了解)
@RequestMapping注解的headers屬性通過請求的請求頭信息匹配請求映射
@RequestMapping注解的headers屬性是一個字符串類型的數(shù)組,可以通過四種表達式設(shè)置請求頭信息和請求映射的匹配關(guān)系
"header"
:要求請求映射所匹配的請求必須攜帶header請求頭信息
"!header"
:要求請求映射所匹配的請求必須不能攜帶header請求頭信息
"header=value"
:要求請求映射所匹配的請求必須攜帶header請求頭信息且header=value
"header!=value"
:要求請求映射所匹配的請求必須攜帶header請求頭信息且header!=value
注意:
若當前請求滿足@RequestMapping注解的value和method屬性,但是不滿足headers屬性,此時頁面顯示404錯誤,即資源未找到。
1.7SpringMVC支持路徑中的占位符(@PathVariable)(重點)
原始方式:/deleteUser?id=1
rest方式:/deleteUser/1
SpringMVC路徑中的占位符常用于RESTful風(fēng)格中,當請求路徑中將某些數(shù)據(jù)通過路徑的方式傳輸?shù)椒?wù)器中,就可以在相應(yīng)的@RequestMapping注解的value屬性中通過占位符{xxx}
表示傳輸?shù)臄?shù)據(jù),在通過==@PathVariable==注解,將占位符所表示的數(shù)據(jù)賦值給控制器方法的形參
<a th:href="@{/testRest/1/admin}" rel="external nofollow" >測試路徑中的占位符-->/testRest</a><br>
@RequestMapping("/testRest/{id}/{username}") public String testRest(@PathVariable("id") String id, @PathVariable("username") String username){ System.out.println("id:"+id+",username:"+username); return "success"; } //最終輸出的內(nèi)容為-->id:1,username:admin
2.SpringMVC獲取請求參數(shù)
2.1通過ServletAPI獲?。私猓?/h3>
將HttpServletReques作為控制器方法的形參,此時HttpServletRequest
類型的參數(shù)表示封裝了當前請求的請求報文的對象
@RequestMapping("/testParam") public String testParam(HttpServletRequest request){ String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("username:"+username+",password:"+password); return "success"; }
2.2通過控制器方法的形參獲取請求參數(shù)
在控制器方法的形參位置,設(shè)置和請求參數(shù)同名的形參,當瀏覽器發(fā)送請求,匹配到請求映射時,在DispatcherServlet
中就會將請求參數(shù)賦值給相應(yīng)的形參
<a th:href="@{/testParam(username='admin',password=123456)}" rel="external nofollow" >測試獲取請求參數(shù)-->/testParam</a><br>
@RequestMapping("/testParam") public String testParam(String username, String password){ System.out.println("username:"+username+",password:"+password); return "success"; }
注:
若請求所傳輸?shù)恼埱髤?shù)中有多個同名的請求參數(shù),此時可以在控制器方法的形參中設(shè)置字符串數(shù)組或者字符串類型的形參接收此請求參數(shù)
若使用字符串數(shù)組類型的形參,此參數(shù)的數(shù)組中包含了每一個數(shù)據(jù)
若使用字符串類型的形參,此參數(shù)的值為每個數(shù)據(jù)中間使用逗號拼接的結(jié)果
2.3@RequestParam
@RequestParam是將請求參數(shù)和控制器方法的形參創(chuàng)建映射關(guān)系
@RequestParam
注解一共有三個屬性:
value:指定為形參賦值的請求參數(shù)的參數(shù)名
required:設(shè)置是否必須傳輸此請求參數(shù),默認值為true
若設(shè)置為true時,則當前請求必須傳輸value所指定的請求參數(shù),若沒有傳輸該請求參數(shù),且沒有設(shè)置defaultValue屬性,則頁面報錯
400:Required String parameter 'xxx' is not present;
若設(shè)置為false,則當前請求不是必須傳輸value所指定的請求參數(shù),若沒有傳輸,則注解所標識的形參的值為null
defaultValue:不管required屬性值為true或false,當value所指定的請求參數(shù)沒有傳輸或傳輸?shù)闹禐?"時,則使用默認值為形參賦值
2.4@RequestHeader
@RequestHeader是將請求頭信息和控制器方法的形參創(chuàng)建映射關(guān)系
@RequestHeader
注解一共有三個屬性:value、required、defaultValue,用法同@RequestParam
2.5@CookieValue
@CookieValue是將**cookie
數(shù)據(jù)**和控制器方法的形參創(chuàng)建映射關(guān)系
@CookieValue
注解一共有三個屬性:value、required、defaultValue,用法同@RequestParam
2.6通過POJO獲取請求參數(shù)
可以在控制器方法的形參位置設(shè)置一個實體類類型的形參,此時若瀏覽器傳輸?shù)恼埱髤?shù)的參數(shù)名和實體類中的屬性名一致,那么請求參數(shù)就會為此屬性賦值
<form th:action="@{/testpojo}" method="post"> 用戶名:<input type="text" name="username"><br> 密碼:<input type="password" name="password"><br> 性別:<input type="radio" name="sex" value="男">男<input type="radio" name="sex" value="女">女<br> 年齡:<input type="text" name="age"><br> /.// 郵箱:<input type="text" name="email"><br> <input type="submit"> </form>
@RequestMapping("/testpojo") public String testPOJO(User user){ System.out.println(user); return "success"; } //最終結(jié)果-->User{id=null, username='張三', password='123', age=23, sex='男', email='123@qq.com'}
3.域?qū)ο蠊蚕頂?shù)據(jù)
3.1使用ServletAPI向request域?qū)ο蠊蚕頂?shù)據(jù)(了解)
@RequestMapping("/testServletAPI") public String testServletAPI(HttpServletRequest request){ request.setAttribute("testScope", "hello,servletAPI"); return "success"; }
3.2使用ModelAndView向request域?qū)ο蠊蚕頂?shù)據(jù)
ModelAndView
有Model
和View
的功能:
Model
主要用于向請求域共享數(shù)據(jù)
View
主要用于設(shè)置視圖,實現(xiàn)頁面跳轉(zhuǎn)
@RequestMapping("/testModelAndView") public ModelAndView testModelAndView(){ /** * ModelAndView有Model和View的功能 * Model主要用于向請求域共享數(shù)據(jù) * View主要用于設(shè)置視圖,實現(xiàn)頁面跳轉(zhuǎn) */ ModelAndView mav = new ModelAndView(); //向請求域共享數(shù)據(jù) mav.addObject("testScope", "hello,ModelAndView"); //設(shè)置視圖,實現(xiàn)頁面跳轉(zhuǎn) mav.setViewName("success"); return mav; }
3.3使用Model向request域?qū)ο蠊蚕頂?shù)據(jù)
@RequestMapping("/testModel") public String testModel(Model model){ model.addAttribute("testScope", "hello,Model"); return "success"; }
3.4使用map向request域?qū)ο蠊蚕頂?shù)據(jù)
@RequestMapping("/testMap") public String testMap(Map<String, Object> map){ map.put("testScope", "hello,Map"); return "success"; }
3.5使用ModelMap向request域?qū)ο蠊蚕頂?shù)據(jù)
@RequestMapping("/testModelMap") public String testModelMap(ModelMap modelMap){ modelMap.addAttribute("testScope", "hello,ModelMap"); return "success"; }
3.6Model、ModelMap、Map的關(guān)系
Model
、ModelMap
、Map
類型的參數(shù)其實本質(zhì)上都是 BindingAwareModelMap
類型的
public interface Model{} public class ModelMap extends LinkedHashMap<String, Object> {} public class ExtendedModelMap extends ModelMap implements Model {} public class BindingAwareModelMap extends ExtendedModelMap {}
3.7向session域共享數(shù)據(jù)
@RequestMapping("/testSession") public String testSession(HttpSession session){ session.setAttribute("testSessionScope", "hello,session"); return "success"; }
3.8向application域共享數(shù)據(jù)
@RequestMapping("/testApplication") public String testApplication(HttpSession session){ ServletContext application = session.getServletContext(); application.setAttribute("testApplicationScope", "hello,application"); return "success"; }
4.HttpMessageConverter
HttpMessageConverter:報文信息轉(zhuǎn)換器,將請求報文轉(zhuǎn)換為Java對象,或?qū)ava對象轉(zhuǎn)換為響應(yīng)報文
HttpMessageConverter
提供了兩個注解和兩個類型:@RequestBody
,@ResponseBody
,RequestEntity
,ResponseEntity
4.1@RequestBody
@RequestBody可以獲取請求體,需要在控制器方法設(shè)置一個形參,使用@RequestBody
進行標識,當前請求的請求體就會為當前注解所標識的形參賦值
<form th:action="@{/testRequestBody}" method="post"> 用戶名:<input type="text" name="username"><br> 密碼:<input type="password" name="password"><br> <input type="submit"> </form>
@RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody String requestBody){ System.out.println("requestBody:"+requestBody); return "success"; } /*輸出結(jié)果: requestBody:username=admin&password=123456 */
4.2RequestEntity
RequestEntity封裝請求報文的一種類型,需要在控制器方法的形參中設(shè)置該類型的形參,當前請求的請求報文就會賦值給該形參,可以通過getHeaders()
獲取請求頭信息,通過getBody()
獲取請求體信息
@RequestMapping("/testRequestEntity") public String testRequestEntity(RequestEntity<String> requestEntity){ System.out.println("requestHeader:"+requestEntity.getHeaders()); System.out.println("requestBody:"+requestEntity.getBody()); return "success"; }
輸出結(jié)果:
requestHeader:[host:"localhost:8080", connection:"keep-alive", content-length:"27", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"", sec-ch-ua-mobile:"?0", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"] requestBody:username=admin&password=123
4.3@ResponseBody
@ResponseBody用于標識一個控制器方法,可以將該方法的返回值直接作為響應(yīng)報文的響應(yīng)體響應(yīng)到瀏覽器
@RequestMapping("/testResponseBody") @ResponseBody public String testResponseBody(){ return "success"; }
結(jié)果:瀏覽器頁面顯示success
4.4@RestController
@RestController注解是springMVC
提供的一個復(fù)合注解,標識在控制器的類上,就相當于為類添加了@Controller
注解,并且為其中的每個方法添加了@ResponseBody
注解
4.5ResponseEntity
ResponseEntity用于控制器方法的返回值類型,該控制器方法的返回值就是響應(yīng)到瀏覽器的響應(yīng)報文
以上就是詳解SpringMVC注解功能及屬性的詳細內(nèi)容,更多關(guān)于SpringMVC注解功能及屬性的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue數(shù)據(jù)響應(yīng)式原理重寫函數(shù)實現(xiàn)數(shù)組響應(yīng)式監(jiān)聽
Vue的通過數(shù)據(jù)劫持的方式實現(xiàn)數(shù)據(jù)的雙向綁定,即使用Object.defineProperty()來實現(xiàn)對屬性的劫持,但是Object.defineProperty()中的setter是無法直接實現(xiàn)數(shù)組中值的改變的劫持行為的,需要的朋友可以參考下2023-05-05idea運行tomcat報錯找不到catalina.bat,系統(tǒng)找不到指定的文件問題
這篇文章主要介紹了idea運行tomcat報錯找不到catalina.bat,系統(tǒng)找不到指定的文件問題,具有很好的參考價值,希望對大家有所幫助,2023-11-11創(chuàng)建Maven項目和Spring IOC實例過程解析
這篇文章主要介紹了創(chuàng)建Maven項目和Spring IOC實例過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12SpringBoot?+?proguard+maven多模塊實現(xiàn)代碼混淆的方法
這篇文章主要介紹了SpringBoot?+?proguard+maven多模塊實現(xiàn)代碼混淆的方法,多模塊跟單模塊一樣,在需要混淆模塊的pom文件中加入proguard依賴及配置,本文給大家講解的非常詳細,感興趣的朋友一起看看吧2024-02-02利用Spring Session和redis對Session進行共享詳解
這篇文章主要給大家介紹了關(guān)于利用Spring、Session和redis對Session進行共享的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09SpringBoot統(tǒng)一返回處理出現(xiàn)cannot?be?cast?to?java.lang.String異常解決
這篇文章主要給大家介紹了關(guān)于SpringBoot統(tǒng)一返回處理出現(xiàn)cannot?be?cast?to?java.lang.String異常解決的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-09-09