引言:
接上一篇文章,對@RequestMapping進行地址映射講解之后,該篇主要講解request 資料到handler method 引數資料的系結所用到的注解和什么情形下使用;
簡介:
handler method 引數系結常用的注解,我們根據他們處理的Request的不同內容部分分為四類:(主要講解常用型別)
A、處理requet uri 部分(這里指uri template中variable,不含queryString部分)的注解: @PathVariable;
B、處理request header部分的注解: @RequestHeader, @CookieValue;
C、處理request body部分的注解:@RequestParam, @RequestBody;
D、處理attribute型別是注解: @SessionAttributes, @ModelAttribute;
1、 @PathVariable
當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable注解系結它傳過來的值到方法的引數上,
示例代碼:
- @Controller
- @RequestMapping("/owners/{ownerId}")
- public class RelativePathUriTemplateController {
-
- @RequestMapping("/pets/{petId}")
- public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
- // implementation omitted
- }
- }
上面代碼把URI template 中變數 ownerId的值和petId的值,系結到方法的引數上,若方法引數名稱和需要系結的uri template中變數名稱不一致,需要在@PathVariable("name")指定uri template中的名稱,2、 @RequestHeader、@CookieValue
@RequestHeader 注解,可以把Request請求header部分的值系結到方法的引數上,
示例代碼:
這是一個Request 的header部分:
Host localhost:8080
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300- @RequestMapping("/displayHeaderInfo.do")
- public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
- @RequestHeader("Keep-Alive") long keepAlive) {
-
- //...
-
- }
上面的代碼,把request header部分的 Accept-Encoding的值,系結到引數encoding上了, Keep-Alive header的值系結到引數keepAlive上,@CookieValue 可以把Request header中關于cookie的值系結到方法的引數上,
例如有如下Cookie值:
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84引數系結的代碼:
- @RequestMapping("/displayHeaderInfo.do")
- public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
-
- //...
-
- }
即把JSESSIONID的值系結到引數cookie上,
3、@RequestParam, @RequestBody
@RequestParam
A) 常用來處理簡單型別的系結,通過Request.getParameter() 獲取的String可直接轉換為簡單型別的情況( String--> 簡單型別的轉換操作由ConversionService配置的轉換器來完成);因為使用request.getParameter()方式獲取引數,所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;
B)用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容,提交方式GET、POST;
C) 該注解有兩個屬性: value、required; value用來指定要傳入值的id名稱,required用來指示引數是否必須系結;
示例代碼:
- @Controller
- @RequestMapping("/pets")
- @SessionAttributes("pet")
- public class EditPetForm {
-
- // ...
-
- @RequestMapping(method = RequestMethod.GET)
- public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
- Pet pet = this.clinic.loadPet(petId);
- model.addAttribute("pet", pet);
- return "petForm";
- }
-
- // ...
@RequestBody
該注解常用來處理Content-Type: 不是application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等;
它是通過使用HandlerAdapter 配置的HttpMessageConverters來決議post data body,然后系結到相應的bean上的,
因為配置有FormHttpMessageConverter,所以也可以用來處理 application/x-www-form-urlencoded的內容,處理完的結果放在一個MultiValueMap<String, String>里,這種情況在某些特殊需求下使用,詳情查看FormHttpMessageConverter api;
示例代碼:
- @RequestMapping(value = https://www.cnblogs.com/blogcpp/p/"/something", method = RequestMethod.PUT)
- public void handle(@RequestBody String body, Writer writer) throws IOException {
- writer.write(body);
- }
4、@SessionAttributes, @ModelAttribute
@SessionAttributes:
該注解用來系結HttpSession中的attribute物件的值,便于在方法中的引數里使用,
該注解有value、types兩個屬性,可以通過名字和型別指定要使用的attribute 物件;
示例代碼:
- @Controller
- @RequestMapping("/editPet.do")
- @SessionAttributes("pet")
- public class EditPetForm {
- // ...
- }
@ModelAttribute
該注解有兩個用法,一個是用于方法上,一個是用于引數上;
用于方法上時: 通常用來在處理@RequestMapping之前,為請求系結需要從后臺查詢的model;
用于引數上時: 用來通過名稱對應,把相應名稱的值系結到注解的引數bean上;要系結的值來源于:
A) @SessionAttributes 啟用的attribute 物件上;
B) @ModelAttribute 用于方法上時指定的model物件;
C) 上述兩種情況都沒有時,new一個需要系結的bean物件,然后把request中按名稱對應的方式把值系結到bean中,
用到方法上@ModelAttribute的示例代碼:
- // Add one attribute
- // The return value of the method is added to the model under the name "account"
- // You can customize the name via @ModelAttribute("myAccount")
-
- @ModelAttribute
- public Account addAccount(@RequestParam String number) {
- return accountManager.findAccount(number);
- }
這種方式實際的效果就是在呼叫@RequestMapping的方法之前,為request物件的model里put(“account”, Account);
用在引數上的@ModelAttribute示例代碼:
- @RequestMapping(value=https://www.cnblogs.com/blogcpp/p/"/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
- public String processSubmit(@ModelAttribute Pet pet) {
-
- }
首先查詢 @SessionAttributes有無系結的Pet物件,若沒有則查詢@ModelAttribute方法層面上是否系結了Pet物件,若沒有則將URI template中的值按對應的名稱系結到Pet物件的各屬性上,補充講解:
問題: 在不給定注解的情況下,引數是怎樣系結的?
通過分析AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter的源代碼發現,方法的引數在不給定引數的情況下:
若要系結的物件時簡單型別: 呼叫@RequestParam來處理的,
若要系結的物件時復雜型別: 呼叫@ModelAttribute來處理的,
這里的簡單型別指java的原始型別(boolean, int 等)、原始型別物件(Boolean, Int等)、String、Date等ConversionService里可以直接String轉換成目標物件的型別;
下面貼出AnnotationMethodHandlerAdapter中系結引數的部分源代碼:
- private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
- NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {
-
- Class[] paramTypes = handlerMethod.getParameterTypes();
- Object[] args = new Object[paramTypes.length];
-
- for (int i = 0; i < args.length; i++) {
- MethodParameter methodParam = new MethodParameter(handlerMethod, i);
- methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
- GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
- String paramName = null;
- String headerName = null;
- boolean requestBodyFound = false;
- String cookieName = null;
- String pathVarName = null;
- String attrName = null;
- boolean required = false;
- String defaultValue = https://www.cnblogs.com/blogcpp/p/null;
- boolean validate = false;
- Object[] validationHints = null;
- int annotationsFound = 0;
- Annotation[] paramAnns = methodParam.getParameterAnnotations();
-
- for (Annotation paramAnn : paramAnns) {
- if (RequestParam.class.isInstance(paramAnn)) {
- RequestParam requestParam = (RequestParam) paramAnn;
- paramName = requestParam.value();
- required = requestParam.required();
- defaultValue = https://www.cnblogs.com/blogcpp/p/parseDefaultValueAttribute(requestParam.defaultValue());
- annotationsFound++;
- }
- else if (RequestHeader.class.isInstance(paramAnn)) {
- RequestHeader requestHeader = (RequestHeader) paramAnn;
- headerName = requestHeader.value();
- required = requestHeader.required();
- defaultValue = https://www.cnblogs.com/blogcpp/p/parseDefaultValueAttribute(requestHeader.defaultValue());
- annotationsFound++;
- }
- else if (RequestBody.class.isInstance(paramAnn)) {
- requestBodyFound = true;
- annotationsFound++;
- }
- else if (CookieValue.class.isInstance(paramAnn)) {
- CookieValue cookieValue = https://www.cnblogs.com/blogcpp/p/(CookieValue) paramAnn;
- cookieName = cookieValue.value();
- required = cookieValue.required();
- defaultValue = https://www.cnblogs.com/blogcpp/p/parseDefaultValueAttribute(cookieValue.defaultValue());
- annotationsFound++;
- }
- else if (PathVariable.class.isInstance(paramAnn)) {
- PathVariable pathVar = (PathVariable) paramAnn;
- pathVarName = pathVar.value();
- annotationsFound++;
- }
- else if (ModelAttribute.class.isInstance(paramAnn)) {
- ModelAttribute attr = (ModelAttribute) paramAnn;
- attrName = attr.value();
- annotationsFound++;
- }
- else if (Value.class.isInstance(paramAnn)) {
- defaultValue = https://www.cnblogs.com/blogcpp/p/((Value) paramAnn).value();
- }
- else if (paramAnn.annotationType().getSimpleName().startsWith("Valid")) {
- validate = true;
- Object value = https://www.cnblogs.com/blogcpp/p/AnnotationUtils.getValue(paramAnn);
- validationHints = (value instanceof Object[] ? (Object[]) value : new Object[] {value});
- }
- }
-
- if (annotationsFound > 1) {
- throw new IllegalStateException("Handler parameter annotations are exclusive choices - " +
- "do not specify more than one such annotation on the same parameter: " + handlerMethod);
- }
-
- if (annotationsFound == 0) {// 若沒有發現注解
- Object argValue = https://www.cnblogs.com/blogcpp/p/resolveCommonArgument(methodParam, webRequest); //判斷WebRquest是否可賦值給引數
- if (argValue != WebArgumentResolver.UNRESOLVED) {
- args[i] = argValue;
- }
- else if (defaultValue != null) {
- args[i] = resolveDefaultValue(defaultValue);
- }
- else {
- Class<?> paramType = methodParam.getParameterType();
- if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {
- if (!paramType.isAssignableFrom(implicitModel.getClass())) {
- throw new IllegalStateException("Argument [" + paramType.getSimpleName() + "] is of type " +
- "Model or Map but is not assignable from the actual model. You may need to switch " +
- "newer MVC infrastructure classes to use this argument.");
- }
- args[i] = implicitModel;
- }
- else if (SessionStatus.class.isAssignableFrom(paramType)) {
- args[i] = this.sessionStatus;
- }
- else if (HttpEntity.class.isAssignableFrom(paramType)) {
- args[i] = resolveHttpEntityRequest(methodParam, webRequest);
- }
- else if (Errors.class.isAssignableFrom(paramType)) {
- throw new IllegalStateException("Errors/BindingResult argument declared " +
- "without preceding model attribute. Check your handler method signature!");
- }
- else if (BeanUtils.isSimpleProperty(paramType)) {// 判斷是否引數型別是否是簡單型別,若是在使用@RequestParam方式來處理,否則使用@ModelAttribute方式處理
- paramName = "";
- }
- else {
- attrName = "";
- }
- }
- }
-
- if (paramName != null) {
- args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler);
- }
- else if (headerName != null) {
- args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler);
- }
- else if (requestBodyFound) {
- args[i] = resolveRequestBody(methodParam, webRequest, handler);
- }
- else if (cookieName != null) {
- args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler);
- }
- else if (pathVarName != null) {
- args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);
- }
- else if (attrName != null) {
- WebDataBinder binder =
- resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler);
- boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1]));
- if (binder.getTarget() != null) {
- doBind(binder, webRequest, validate, validationHints, !assignBindingResult);
- }
- args[i] = binder.getTarget();
- if (assignBindingResult) {
- args[i + 1] = binder.getBindingResult();
- i++;
- }
- implicitModel.putAll(binder.getBindingResult().getModel());
- }
- }
-
- return args;
- }
RequestMappingHandlerAdapter中使用的引數系結,代碼稍微有些不同,有興趣的同仁可以分析下,最后處理的結果都是一樣的,
示例:
- @RequestMapping ({"/", "/home"})
- public String showHomePage(String key){
-
- logger.debug("key="+key);
-
- return "home";
- }
這種情況下,就呼叫默認的@RequestParam來處理,
- @RequestMapping (method = RequestMethod.POST)
- public String doRegister(User user){
- if(logger.isDebugEnabled()){
- logger.debug("process url[/user], method[post] in "+getClass());
- logger.debug(user);
- }
-
- return "user";
- }
這種情況下,就呼叫@ModelAttribute來處理,
參考檔案:
1、 Spring Web Doc:
spring-3.1.0/docs/spring-framework-reference/html/mvc.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/151695.html
標籤:Java
上一篇:第七章第三題(計算數字的出現次數)(Count occurrence of numbers) - 編程練習題答案
下一篇:若感染病毒的是你,你又該如何?
