The table below shows supported controller method arguments. Reactive types are not supported for any arguments.java
下表顯示支持的控制器方法參數。 任何參數都不支持反應類型。react
Controller method argumentweb |
Descriptionspring |
WebRequest, NativeWebRequest編程 |
通用訪問請求參數,請求和會話屬性,不須要直接使用Servlet API。json |
javax.servlet.ServletRequest, javax.servlet.ServletResponseapi |
選擇任何特定的請求或響應類型 - 例如 ServletRequest,HttpServletRequest或Spring的MultipartRequest,MultipartHttpServletRequest。安全 |
javax.servlet.http.HttpSessionspringboot |
強制進行會話。 結果,這樣的論證永遠不會爲空。 注意:會話訪問不是線程安全的。 若是容許多個請求同時訪問會話,請考慮將RequestMappingHandlerAdapter的「synchronizeOnSession」標誌設置爲「true」。 |
javax.servlet.http.PushBuilder |
用於編程式HTTP / 2資源推送的Servlet 4.0 push builder API。 請注意,根據Servlet規範,若是客戶端不支持HTTP / 2功能,則注入的PushBuilder實例能夠爲null。 |
java.security.Principal |
Currently authenticated user; possibly a specific Principal implementation class if known. 目前已經過身份驗證 若是知道的話多是一個特定的主體實現類 |
HttpMethod |
The HTTP method of the request. |
java.util.Locale |
The current request locale, determined by the most specific LocaleResolver available, in effect, the configured LocaleResolver/LocaleContextResolver. 他當前的請求語言環境,由最具體的LocaleResolver肯定,其實是配置的LocaleResolver / LocaleContextResolver。 |
java.util.TimeZone + java.time.ZoneId |
The time zone associated with the current request, as determined by a LocaleContextResolver. 與當前請求關聯的時區,由LocaleContextResolver肯定 |
java.io.InputStream, java.io.Reader |
For access to the raw request body as exposed by the Servlet API. 用於訪問由Servlet API公開的原始請求主體。 |
java.io.OutputStream, java.io.Writer |
For access to the raw response body as exposed by the Servlet API. 用於訪問由Servlet API公開的原始響應主體。 |
@PathVariable |
For access to URI template variables. See URI patterns. 用於訪問URI模板變量。 請參閱URI模式。 |
@MatrixVariable |
For access to name-value pairs in URI path segments. See Matrix variables. 用於訪問URI路徑段中的名稱/值對。 請參閱矩陣變量。 |
@RequestParam |
For access to Servlet request parameters. Parameter values are converted to the declared method argument type. See @RequestParam. Note that use of @RequestParam is optional, e.g. to set its attributes. See "Any other argument" further below in this table. 請注意,使用@RequestParam是可選的,例如, 設置其屬性。 請參閱本表下面的「任何其餘參數」。 主要用於在SpringMVC後臺控制層獲取參數,相似一種是request.getParameter("name"), 它有三個經常使用參數: defaultValue = "0", required = false, value = "isApp"; defaultValue 表示設置默認值, required 銅過boolean設置是不是必需要傳入的參數, value 值表示接受的傳入的參數類型。 @RequestParam將請求的參數綁定到方法中的參數上,以下面的代碼所示。其實,即便不配置該參數,註解也會默認使用該參數。若是想自定義指定參數的話,若是將@RequestParam的 required 屬性設置爲false(如@RequestParam(value="id",required=false))。 |
@RequestHeader |
For access to request headers. Header values are converted to the declared method argument type. See @RequestHeader. 用於訪問請求標題。 標題值被轉換爲聲明的方法參數類型。 請參閱@RequestHeader。 |
@CookieValue |
For access to cookies. Cookies values are converted to the declared method argument type. See @CookieValue. 用於訪問cookie。 Cookies值被轉換爲聲明的方法參數類型。 請參閱@CookieValue。 |
@RequestBody |
For access to the HTTP request body. Body content is converted to the declared method argument type using HttpMessageConverters. See @RequestBody. 用於訪問HTTP請求主體。 使用HttpMessageConverters將主體內容轉換爲聲明的方法參數類型。 請參閱@RequestBody。 請求的body體的綁定(經過HttpMessageConverter進行類型轉換); 做用: 該註解用於將Controller的方法返回的對象,經過適當的HttpMessageConverter轉換爲指定格式後,寫入到Response對象的body數據區。 使用時機:返回的數據不是html標籤的頁面,而是其餘某種格式的數據時(如json、xml等)使用; |
HttpEntity<B> |
For access to request headers and body. The body is converted with HttpMessageConverters. See HttpEntity. 用於訪問請求標頭和正文。 正文使用HttpMessageConverters進行轉換。 請參閱HttpEntity。 |
@RequestPart |
For access to a part in a "multipart/form-data" request. See Multipart. 用於訪問「multipart / form-data」請求中的部分。 見多部分。 |
java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMap |
For access to the model that is used in HTML controllers and exposed to templates as part of view rendering. 用於訪問HTML控制器中使用的模型,並將其做爲視圖渲染的一部分展現給模板。 |
RedirectAttributes |
Specify attributes to use in case of a redirect — i.e. to be appended to the query string, and/or flash attributes to be stored temporarily until the request after redirect. See Redirect attributes and Flash attributes. 指定要重定向時使用的屬性 - 即要追加到查詢字符串,和/或臨時存儲的閃存屬性,直到重定向後的請求。 請參閱重定向屬性和Flash屬性。 |
@ModelAttribute |
For access to an existing attribute in the model (instantiated if not present) with data binding and validation applied. See @ModelAttribute as well as Model and DataBinder. Note that use of @ModelAttribute is optional, e.g. to set its attributes. See "Any other argument" further below in this table. 用於訪問模型中的現有屬性(若是不存在,則實例化),並應用數據綁定和驗證。 請參閱@ModelAttribute以及Model和DataBinder。 請注意,@ModelAttribute的使用是可選的,例如 設置其屬性。 請參閱本表下面的「任何其餘參數」。 |
Errors, BindingResult |
For access to errors from validation and data binding for a command object (i.e. @ModelAttribute argument), or errors from the validation of an @RequestBody or @RequestPart arguments; an Errors, or BindingResult argument must be declared immediately after the validated method argument. 用於訪問命令對象(即@ModelAttribute參數)的驗證和數據綁定中的錯誤,或來自驗證@RequestBody或@RequestPart參數的錯誤; 必須在驗證的方法參數後當即聲明Errors或BindingResult參數。 |
SessionStatus+class-level @SessionAttributes |
For marking form processing complete which triggers cleanup of session attributes declared through a class-level @SessionAttributes annotation. See @SessionAttributes for more details. 用於標記表單處理完成,觸發清理經過類級別@SessionAttributes註釋聲明的會話屬性。 有關更多詳細信息,請參閱@SessionAttributes |
UriComponentsBuilder |
For preparing a URL relative to the current request’s host, port, scheme, context path, and the literal part of the servlet mapping also taking into account Forwarded and X-Forwarded-* headers. See URI Links. 用於準備相對於當前請求的主機,端口,方案,上下文路徑以及servlet映射的文字部分的URL,同時也考慮了轉發和X-Forwarded- *標頭。 請參閱URI連接。 |
@SessionAttribute |
For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level @SessionAttributes declaration. See @SessionAttribute for more details. 用於訪問任何會話屬性; 與經過類級別@SessionAttributes聲明存儲在會話中的模型屬性相反。 有關更多詳細信息,請參閱@SessionAttribute。 |
@RequestAttribute |
For access to request attributes. See @RequestAttribute for more details. 用於訪問請求屬性。 有關更多詳細信息,請參閱@RequestAttribute。 |
Any other argument 這個參數能夠是任意類型,也能夠是一個實體類,SpringMVC會自動封裝 |
If a method argument is not matched to any of the above, by default it is resolved as an @RequestParam if it is a simple type, as determined by BeanUtils#isSimpleProperty, or as an @ModelAttribute otherwise. 若是方法參數與上述任何一個不匹配,默認狀況下,它被解析爲一個@RequestParam,若是它是一個簡單的類型,如BeanUtils#isSimpleProperty所肯定的,或者做爲@ModelAttribute來肯定。 |
下面是具體使用說明,幾乎都是下面這種格式:
Public String (@RequestParam int id){..}
@RequestParam用來接收路徑後面的參數 http:www.lifeibai.com?petId = 1.
通常用來處理接收的參數和形參的參數不一致的狀況
value:參數名字,即入參的請求參數名字,如value=「item_id」表示請求的參數區中的名字爲item_id的參數的值將傳入;
required:是否必須,默認是true,表示請求中必定要有相應的參數,不然將報;
TTP Status 400 - Required Integer parameter 'XXXX' is not present
defaultValue:默認值,表示若是請求中沒有同名參數時的默認值
@Controller
@RequestMapping("/pets")
public class EditPetForm {
// ...
@GetMapping
public String setupForm(@RequestParam("petId") int Id, Model model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
// ...
}
@RequestParam(value = "id",defaultValue = "10",required = false)
defaultValue 表示設置默認值,
required 銅過boolean設置是不是必需要傳入的參數,
value 值表示接受的傳入的參數類型
使用@RequestParam經常使用於處理簡單類型的綁定。
value:參數名字,即入參的請求參數名字,如value=「item_id」表示請求的參數區中的名字爲item_id的參數的值將傳入;
required:是否必須,默認是true,表示請求中必定要有相應的參數,不然將報;
TTP Status 400 - Required Integer parameter 'XXXX' is not present
defaultValue:默認值,表示若是請求中沒有同名參數時的默認值
定義以下:
public String editItem(@RequestParam(value="item_id",required=true) String id) {
}
形參名稱爲id,可是這裏使用value=" item_id"限定請求的參數名爲item_id,因此頁面傳遞參數的名必須爲item_id。
注意:若是請求參數中沒有item_id將跑出異常:
HTTP Status 500 - Required Integer parameter 'item_id' is not present
這裏經過required=true限定item_id參數爲必需傳遞,若是不傳遞則報400錯誤,可使用defaultvalue設置默認值,即便required=true也能夠不傳item_id參數值
@RequestHeader用來接收指定參數的請求頭信息
@GetMapping("/demo")
public void handle(
@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
//...
}
用來接收指定名稱的cookie的值
@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) {
//...
}
ModelAttribute能夠應用在方法參數上或方法上,他的做用主要是當註解在方法參數上時會將註解的參數對象添加到Model中;
當註解在請求處理方法Action上時會將該方法變成一個非請求處理的方法,但其它Action被調用時會首先調用該方法。
被@ModelAttribute註釋的方法會在此controller每一個方法執行前被執行,下面訪問http:localhost:8080/test_project/test.action
@RestController
@SessionAttributes("user")
public class TestController {
@ModelAttribute("age2")
public String mdoeltest1(){
System.out.println("This is ModelAttribute1 !");
return "33";
}
@ModelAttribute("age1")
public String mdoeltestrrr(){
System.out.println("This is ModelAttributee1 !");
return "22";
}
@RequestMapping("/test.action")
public String test(User user ,
@ModelAttribute("age1") String age1 ,
@ModelAttribute("age2") String age2 ,
HttpSession session){
Object user2 = session.getAttribute("user");
System.out.println(user2);
System.out.println(user);
System.out.println("age1:"+age1);
System.out.println("age2:"+age2);
return "test";
}
}
結果:
This is ModelAttributee1 !
This is ModelAttribute1 !
User{name='李四', age=22}
User{name='李四', age=22}
age1:22
age2:33
Value={「name」,「age」} 取出name或者value、或者把model中的name,age扔到session中
Type=User。Class 將一個實體類扔到session中
這個玩意加在 類上面,而後全部的方法的參數均可以在sesssion中找,找到了就賦值。
@SessionAttributes須要清除時,使用SessionStatus.setComplete();來清除。
一、 將model中的值,扔到session中
@Controller
@SessionAttributes(types = User.class)
public class LoginController {
@RequestMapping("/login")
public String login(HttpServletRequest req,Model model,SessionStatus status){
User user = new User();
user.setName("李四");
user.setAge(22);
model.addAttribute("user" , user);
return "forward:test.action";
}
}
二、 從session取出來
@RestController
@SessionAttributes("user")
public class TestController {
@RequestMapping("/test.action")
public String test(User user, HttpSession session){
Object user2 = session.getAttribute("user");
System.out.println(user2);
System.out.println(user);
return "test";
}
}
這玩意是加在方法上的參數的,將session中的數據賦值給參數
@RequestMapping("/")
public String handle(@SessionAttribute User user) {
// ...
}
這玩意是接收request域中的數據的
@GetMapping("/")
public String handle(@RequestAttribute Client client) {
// ...
}
做用:
@RequestBody註解用於讀取http請求的內容(字符串),經過springmvc提供的HttpMessageConverter接口將讀到的內容轉換爲json、xml等格式的數據並綁定到controller方法的參數上。
List.action?id=1&name=zhangsan&age=12
本例子應用:
@RequestBody註解實現接收http請求的json數據,將json數據轉換爲java對象
// 商品修改提交json信息,響應json信息
@RequestMapping("/editItemSubmit_RequestJson")
public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {
System.out.println(items);
//itemService.saveItem(items);
return items;
}
做用:
該註解用於將Controller的方法返回的對象,經過HttpMessageConverter接口轉換爲指定格式的數據如:json,xml等,經過Response響應給客戶端
本例子應用:
@ResponseBody註解實現將controller方法返回對象轉換爲json響應給客戶端
使用這個註解 ,sessionAttributes註解將會失效
簡介
@PathVariable用於將請求URL中的模板變量映射到功能處理方法的參數上。
用法
@RequestMapping(value="/users/{userId}/topics/{topicId}")
public String test(
@PathVariable(value="userId") int userId,
@PathVariable(value="topicId") int topicId)
如請求的URL爲「控制器URL/users/123/topics/456」,則自動將URL中模板變量{userId}和{topicId}綁定到經過@PathVariable註解的同名參數上,即入參後userId=12三、topicId=456。
ModelMap是Model接口的實現類,經過Model或ModelMap向頁面傳遞數據,以下:
@RequestMapping("/itemEdit")
public String itemEdit(Integer id, Model model) {
Items items = itemService.getItemById(id);
//向jsp傳遞數據
model.addAttribute("item", items);
//設置跳轉的jsp頁面
return "editItem";
}
/*@RequestMapping("/itemEdit")
public String editItem(HttpServletRequest request,
HttpServletResponse response, HttpSession session, Model model) {
//從request中取參數
String strId = request.getParameter("id");
int id = new Integer(strId);
//調用服務
Items items = itemService.getItemById(id);
//把結果傳遞給頁面
//ModelAndView modelAndView = new ModelAndView();
//modelAndView.addObject("item", items);
//設置邏輯視圖
//modelAndView.setViewName("editItem");
//return modelAndView;
//設置返回結果
model.addAttribute("item", items);
//返回邏輯視圖
return "editItem";
}
*/
當請求的參數名稱和處理器形參名稱一致時會將請求參數與形參進行綁定。從Request取參數的方法能夠進一步簡化。
@RequestMapping("/itemEdit")
public String itemEdit(Integer id, Model model) {
Items items = itemService.getItemById(id);
//向jsp傳遞數據
model.addAttribute("item", items);
//設置跳轉的jsp頁面
return "editItem";
}
參數類型推薦使用包裝數據類型,由於基礎數據類型不能夠爲null
整形:Integer、int
字符串:String
單精度:Float、float
雙精度:Double、double
布爾型:Boolean、boolean
說明:對於布爾類型的參數,請求的參數值爲true或false。
處理方法:
public String editItem(Model model,Integer id,Boolean status) throws Exception
請求url:
http://localhost:8080/xxx.action?id=2&status=false
處理器形參中添加以下類型的參數處理適配器會默認識別並進行賦值。
經過request對象獲取請求信息
經過response處理響應信息
經過session對象獲得session中存放的對象
s=false