SpringMVC中,如何處理請求是很重要的任務。請求映射都會使用@RequestMapping標註。其中,類上的標註相當於一個首碼,表示該處理器是處理同一類請求;方法上的標註則更加細化。如,類的標註可能是“user”,表示全部都是與用戶相關的操作;具體到方法可能有“create”“update”“ ...
SpringMVC中,如何處理請求是很重要的任務。請求映射都會使用@RequestMapping標註。其中,類上的標註相當於一個首碼,表示該處理器是處理同一類請求;方法上的標註則更加細化。如,類的標註可能是“user”,表示全部都是與用戶相關的操作;具體到方法可能有“create”“update”“delete”等,分別表示對用戶進行哪一類操作。
package cn.javass.chapter6.web.controller; @Controller @RequestMapping(value="/user") //①處理器的通用映射首碼 public class HelloWorldController2 { @RequestMapping(value = "/hello2") //②相對於①處的映射進行窄化 public ModelAndView helloWorld() { //省略實現 } }
現在就來總結一下請求映射有哪些。
一、URL路徑映射
這種映射涉及的屬性只有value。
@RequestMapping(value={"/test1", "/user/create"}) //或,表示多個路徑都可以映射到同一個處理方法 @RequestMapping(value="/users/{userId}/topics/{topicId}") //也可以使用大括弧,表示變數占位符 @RequestMapping(value="/product?") //可匹配“/product1”或“/producta”,但不匹配“/product”或“/productaa” @RequestMapping(value="/products/**/{productId}") //可匹配“/products/abc/abc/123”或“/products/123” @RequestMapping(value="/products/{categoryCode:\\d+}-{pageNumber:\\d+}") //支持正則表達式
二、請求方法映射限定
不僅要提供value屬性,還要提供method屬性。
@RequestMapping(value="/create", method = RequestMethod.GET) //表示可處理匹配“/create”且請求方法為“GET”的請求 @RequestMapping(value="/create", method = RequestMethod.POST) //表示可處理匹配“/create”且請求方法為“POST”的請求
一般瀏覽器僅支持GET和POST類型,其他如PUT、DELETE等需要進行模擬。
三、請求參數映射限定
需要提供params屬性和method屬性。
以下麵的控制器為例,
@Controller @RequestMapping("/parameter1") //①處理器的通用映射首碼 public class RequestParameterController1 { // Something... }
@RequestMapping(params="create", method=RequestMethod.GET) //表示請求中有“create”的參數名且請求方法為“GET”即可匹配, 如可匹配的請求URL“http://×××/parameter1?create” @RequestMapping(params="create", method=RequestMethod.POST) //表示請求中有“create”的參數名且請求方法為“POST”即可匹配 @RequestMapping(params="!create", method=RequestMethod.GET) //表示請求中沒有“create”參數名且請求方法為“GET”即可匹配, 如可匹配的請求URL“http://×××/parameter1?abc” @RequestMapping(params="submitFlag=create", method=RequestMethod.GET) //表示請求中有“submitFlag=create”請求參數且請求方法為“GET”即可匹配, 如請求URL為http://×××/parameter2?submitFlag=create @RequestMapping(params="submitFlag=create", method=RequestMethod.POST) //表示請求中有“submitFlag=create”請求參數且請求方法為“POST”即可匹配 @RequestMapping(params="submitFlag=create", method=RequestMethod.GET) //表示請求中有“submitFlag=create”請求參數且請求方法為“GET”即可匹配, 如請求URL為http://×××/parameter2?submitFlag=create
與value中的參數組合表示“或”不同,params參數組合表示“且”,即:
@RequestMapping(params={"test1", "test2=create"}) //表示請求中的有“test1”參數名 且 有“test2=create”參數即可匹配,如可匹配的請求URL“http://×××/parameter3?test1&test2=create