[@Controller]2 詳解@RequestMapping

[@Controller]2 詳解@RequestMapping

 (2012-06-14 15:41:06)

A、@RequestMapping

org.springframework.web.bind.annotation.RequestMapping

Annotation for mapping web requests onto specific handler classes and/or handler methods. Provides consistent style between Servlet and Portlet environments, with the semantics adapting to the concrete environment.

@RequestMapping註釋它把web請求映射到特定的處理器類和/或處理器方法。它支持Servlet和Portlet環境,並在這兩種環境中定義相同。

NOTE: Method-level mappings are only allowed to narrow the mapping expressed at the class level (if any). In the Servlet case, an HTTP path needs to uniquely map onto one specific handler bean (not spread across multiple handler beans); the remaining mapping parameters and conditions are effectively assertions only. In the Portlet case, a portlet mode in combination with specific parameter conditions needs to uniquely map onto one specific handler bean, with all conditions evaluated for mapping purposes. It is strongly recommended to co-locate related handler methods into the same bean and therefore keep the mappings simple and intuitive.

注,定義在方法上的@RequestMapping只允許縮小定義在類上的@RequestMapping的映射範圍(如果類上有定義的話)。在Servlet情況中,一個HTTP路徑需要唯一的映射到一個指定的處理器bean,其它的映射參數和條件有效聲明。在Portlet情況中,

Handler methods which are annotated with this annotation are allowed to have very flexible signatures. They may have arguments of the following types, in arbitrary order (except for validation results, which need to follow right after the corresponding command object, if desired):

處理器方法的@RequestMapping註釋方法非常靈活。它可能有以下幾種類型

 

A.1、@RequestMapping類型

類級別(Type-level),就是註釋定義在類定義的上面。

方法級別(Method-level),就是註釋定義在方法定義的上面。

舉例說明

@Controller

@RequestMapping("/a")

public class HelloWorldController {

    @RequestMapping("/helloWorld")

    public String helloWorld(Model model) {

       model.addAttribute("message", "Hello World!");

       return "helloWorld";

    }

}

@RequestMapping("/a")爲類級別(Class-level),@RequestMapping("/helloWorld")爲方法級別(Method-level)。這個例子是把請求地址/a/helloWorld映射到helloWorld處理器上。

 

A.2、@RequestMapping的屬性

A.2.1、value

The primary mapping expressed by this annotation.

通過這個註釋表達主要的映射。

In a Servlet environment: the path mapping URIs (e.g. "/myPath.do"). Ant-style path patterns are also supported (e.g. "/myPath/*.do"). At the method level, relative paths (e.g. "edit.do") are supported within the primary mapping expressed at the type level.

在Servlet環境中,映射路徑(如,/myPath.do),也支持Any風格的(如,/myPath/*.do)。在方法級別中的相對路徑需要類級別的主路徑支持。

@RequestMapping("/a")就等同於@RequestMapping(value="/a")

 

A.2.2、method

The HTTP request methods to map to, narrowing the primary mapping: GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE.

通過HTTP請求的method來縮小主映射的範圍。GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE.

Supported at the type level as well as at the method level!

支持定義在類級別或方法級別。

@RequestMapping(value="/b",method=RequestMethod.POST)

   

A.2.3、params

The parameters of the mapped request, narrowing the primary mapping.

通過映射請求的參數來縮小主映射的範圍。

Same format for any environment: a sequence of "myParam=myValue" style expressions, with a request only mapped if each such parameter is found to have the given value. Expressions can be negated by using the "!=" operator, as in "myParam!=myValue". "myParam" style expressions are also supported, with such parameters having to be present in the request (allowed to have any value). Finally, "!myParam" style expressions indicate that the specified parameter is not supposed to be present in the request.

在任何環境下,"myParam=myValue"風格的表達式,只有當請求有這樣的參數映射纔會被執行。可通過"!="操作符來表示否定,如"myParam!=myValue"。"myParam"風格的表達式也支持,主要在請求中出現該參數不管值爲多少。"!myParam"的表達式表示指定的參數不能在請求中出現。

Supported at the type level as well as at the method level!

支持定義在類級別或方法級別。

@RequestMapping(value="/b",params="myParam")

 

A.2.4、headers

The headers of the mapped request, narrowing the primary mapping.

通過請求的header來縮小主映射的範圍。

Same format for any environment: a sequence of "My-Header=myValue" style expressions, with a request only mapped if each such header is found to have the given value. Expressions can be negated by using the "!=" operator, as in "My-Header!=myValue". "My-Header" style expressions are also supported, with such headers having to be present in the request (allowed to have any value). Finally, "!My-Header" style expressions indicate that the specified header is not supposed to be present in the request.

在任何環境下,"My-Header=myValue"風格的表達式,只有當請求有這樣的header纔會被執行。可通過"!="操作符來表示否定,如"My-Header!=myValue"。"My-Header"風格的表達式也支持,主要在請求中出現該header不管值爲多少。"!My-Header"的表達式表示指定的header不能在請求中出現。

Also supports media type wildcards (*), for headers such as Accept and Content-Type. For instance,

也支持(*),例如,

@RequestMapping(value = "/something", headers = "content-type=text/*")

 

A.3、相關方法支持的返回類型

The following return types are supported for handler methods:

支持以下處理器方法(被@RequestMapping註釋的方法)的返回類型:

A.3.1、ModelAndView

A ModelAndView object (Servlet MVC or Portlet MVC), with the model implicitly enriched with command objects and the results of ModelAttribute annotated reference data accessor methods.

ModelAndView(Servlet或Portlet),這個模式隱含command對象和@ ModelAttribute註釋的結果。

舉例說明

@RequestMapping("/hello.do")   

    public ModelAndView helloWorld() {

       ModelAndView mv=new ModelAndView();

       mv.setViewName("helloWorld");

       mv.addObject("attributeName", "attributeValue");

       return mv;

    }

通過ModelAndView構造方法可以指定返回的頁面名稱,也可以通過setViewName()方法指定頁面名稱,使用addObject()設置需要返回的值,addObject()有幾個不同參數的方法,可以默認和指定返回對象的名字。調用addObject()方法將值設置到一個名爲ModelMap的類屬性,ModelMap是LinkedHashMap的子類,具體請看類。

A.3.2、Model

A Model object, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of ModelAttribute annotated reference data accessor methods.

返回一個Model對象來表示模型,而視圖名則利用RequestToViewNameTranslator把請求轉換爲視圖名稱。

舉例說明

@RequestMapping("/helloWorld.do")

    public Model helloWorld() {

       Model model=new ExtendedModelMap();

       model.addAttribute("attributeName", "attributeNameValue2");

       return model;

    }

這裏用Model的一個實現ExtendedModelMap來表示model,RequestToViewNameTranslator把請求"/helloWorld.do"轉換爲視圖名爲helloWorld。若請求爲/a/b.form,則視圖名爲a/b。

A.3.3、Map

A Map object for exposing a model, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of ModelAttribute annotated reference data accessor methods.

返回一個Map對象來表示模型,而視圖名則利用RequestToViewNameTranslator把請求轉換爲視圖名稱。

舉例說明

    @RequestMapping("/helloWorld.do")

    public Map<String, String> helloWorld() {

       Map<String, String> map = new HashMap<String, String>();

       map.put("attributeName", "attributeNameValue");

       return map;

    }

這裏用map表示model,RequestToViewNameTranslator把請求"/helloWorld.do"轉換爲視圖名爲helloWorld。若請求爲/a/b.form,則視圖名爲a/b。

A.3.4、View

A View object, with the model implicitly determined through command objects and ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).

A.3.5、String

A String value which is interpreted as view name, with the model implicitly determined through command objects and ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a ModelMap argument (see above).

返回一個Map對象來表示視圖名,處理器中對於的方法也可以通過聲明一個ModelMap的參數來表示model。

舉例說明

@RequestMapping("/helloWorld.do")

    public String helloWorld(ModelMap model) {

       model.addAttribute("attributeName", "attributeNameValue3");

       return "helloWorld";

}

這裏返回的字符串"helloWorld"表示視圖名稱,而ModelMap類型的參數表示model。也可以把參數定義爲Model類型。

A.3.6、@ResponseBody

@ResponseBody annotated methods for access to the Servlet response HTTP contents. The return value will be converted to the response stream using message converters.

一個方法用@ResponseBody來註釋,表示這個方法將直接響應HTTP內容。

詳見C、@ResponseBody

A.3.7、HttpEntity<?> ResponseEntity<?>

A HttpEntity<?> or ResponseEntity<?> object to access to the Servlet reponse HTTP headers and contents. The entity body will be converted to the response stream using message converters.

A.3.8、void

void if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse / HttpServletResponse / RenderResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature; only applicable in a Servlet environment).

返回空void表示方法自己處理響應,一種辦法是:通過聲明一個ServletResponse或HttpServletResponse或RenderResponse類型的參數來直接輸出響應內容,第二種是:通過RequestToViewNameTranslator把請求轉化爲視圖名,此方法不用在處理方法中聲明一個response參數,不過這種方法是能在Servlet環境下使用。

舉例說明

@RequestMapping("/helloWorld.do")

    public void helloWorld(ModelMap model) {

       model.addAttribute("attributeName", "attributeNameValue3");

}

這是上面提及的方法的第二種,把請求"/helloWorld.do"轉換爲視圖名稱helloWorld。和返回String一樣可聲明一個ModelMap參數來表示model。

A.3.9、other return type

Any other return type will be considered as single model attribute to be exposed to the view, using the attribute name specified through ModelAttribute at the method level (or the default attribute name based on the return type's class name otherwise). The model will be implicitly enriched with command objects and the results of ModelAttribute annotated reference data accessor methods.

 

A.4、相關方法支持的參數類型

A.4.1、Request或response

Request or response objects (Servlet API). Choose any specific request or response type, for example ServletRequest or HttpServletRequest.

Request或response對象(Servlet)。例如,ServletRequest或HttpServletRequest。

A.4.2、Session

Session object (Servlet API): of type HttpSession. An argument of this type enforces the presence of a corresponding session. As a consequence, such an argument is never null.

Session對象(Servlet),HttpSession。這種類型的參數它強制一個相關的session存在。因此這個參數永遠不會爲空。

A.4.3、WebRequest或NativeWebRequest

org.springframework.web.context.request.WebRequest or org.springframework.web.context.request.NativeWebRequest. Allows for

generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.

WebRequest或NativeWebRequest。它允許像訪問request或session屬性一樣訪問一般的請求參數,不需要使用Servlet/Portlet API。

A.4.4、Locale

java.util.Locale for the current request locale, determined by the most specific locale resolver available, in effect, the configured LocaleResolver in a Servlet environment.

Locale用於當前請求的Locale,這個Locale由指定的LocaleResolver決定。

A.4.5、InputStream或Reader

java.io.InputStream / java.io.Reader for access to the request's content. This value is the raw InputStream/Reader as exposed by the Servlet API.

InputStream或Reader用於訪問請求的內容。

A.4.6、OutputStream或Writer

java.io.OutputStream / java.io.Writer for generating the response's content. This value is the raw OutputStream/Writer as exposed by the Servlet API.

OutputStream或Writer用於生成響應內容。

A.4.7、Principal

java.security.Principal containing the currently authenticated user.

A.4.8、@PathVariable

@PathVariable annotated parameters for access to URI template variables.

@PathVariable註釋的這個參數用於訪問URI template變量。

A.4.9、@RequestParam

@RequestParam annotated parameters for access to specific Servlet request parameters. Parameter values are converted to the declared method argument type.

@RequestParam註釋參數用於訪問特定的servlet請求參數。參數的值將被轉換爲聲明的參數類型。

A.4.10、@RequestHeader

@RequestHeader annotated parameters for access to specific Servlet request HTTP headers.Parameter values are converted to the declared method argument type.

@RequestHeader註釋參數用於訪問特定的servlet請求的HTTP頭。參數的值將被轉換爲聲明的參數類型。

A.4.11、@RequestBody

@RequestBody annotated parameters for access to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters.

@RequestBody註釋參數用於訪問HTTP請求內容。HttpMessageConverters把參數的值轉換爲聲明的參數類型。

A.4.12、@RequestPart

@RequestPart annotated parameters for access to the content of a "multipart/form-data" request part.

@RequestPart註釋參數用於訪問"multipart/form-data"請求部分的內容。

A.4.13、HttpEntity<?>

HttpEntity<?> parameters for access to the Servlet request HTTP headers and contents. The request stream will be converted to the entity body using HttpMessageConverters.

HttpEntity<?>參數用於訪問servlet請求的HTTP頭和內容。請求流將被HttpMessageConverters轉換爲實體的內容。

A.4.13、Map、Model或ModelMap

java.util.Map / org.springframework.ui.Model /

org.springframework.ui.ModelMap for enriching the implicit model that is exposed to the web view.

Map、Model或ModelMap用於充實提供給web視圖的隱含model。

A.4.14、RedirectAttributes org.springframework.web.servlet.mvc.support.RedirectAttributes to specify the exact set of attributes to use in case of a redirect and also to add flash attributes (attributes stored temporarily on the server-side to make them available to the request after the redirect).

RedirectAttributes is used instead of the implicit model if the method returns a "redirect:"prefixed view name or RedirectView.

A.4.15、command/form object(@ModelAttribute)

Command or form objects to bind request parameters to bean properties (via setters) or directly to fields, with customizable type conversion, depending on @InitBinder methods and/or the HandlerAdapter configuration. See the webBindingInitializer property on RequestMappingHandlerAdapter. Such command objects along with their validation results will be exposed as model attributes by default, using the command class class name - e.g. model attribute "orderAddress" for a command object of type "some.package.OrderAddress". The ModelAttribute annotation can be used on a method argument to customize the model attribute name used.

把Command對象或表單對象將請求參數綁定到bean的屬性(通過setters)或直接綁定到字段上,使用自定義的類型轉換器,依賴@InitBinder方法和HandlerAdapter配置(參考,RequestMappingHandlerAdapter的webBindingInitializer屬性)。默認情況下,這樣的command對象連同它們的驗證結果將作爲一個模型屬性對外提供。@ModelAttribute註釋可用於聲明一個方法參數來自定義模型屬性名稱使用。

A.4.16、Errors或BindingResult

org.springframework.validation.Errors /org.springframework.validation.BindingResult validation results for a preceding command or form object.

Errors或BindingResult用於配合command/form object使用。

A.4.17、SessionStatus

org.springframework.web.bind.support.SessionStatus status handle for marking form processing as complete, which triggers the cleanup of session attributes that have been indicated by the @SessionAttributes annotation at the handler type level.

SessionStatus狀態處理用於把表單處理過程標記爲已完成,它觸發清理session屬性,這些被清理的session屬性是由@SessionAttributes註釋在處理器類級別定義的。

A.4.18、UriComponentsBuilder

org.springframework.web.util.UriComponentsBuilder a builder for preparing a URL relative to the current request's host, port, scheme, context path, and the literal part of the servlet mapping.

 

A.5、URI template(URI模板)

URI是指@RequestMapping(“URI”),也就是RequestMapping的value屬性。

URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.

URI template用於@RequestMapping方法訪問URL的選中的部分。

URI template規則定義在http://code.google.com/p/uri-templates/

一個URI template,可以包含多個變量名稱(這些變量名稱有{}括起來)。例如,一個URI template是:http://www.example.com/users/{userId}它包含一個userId變量。這時我們需要用@PathVariable來把URI template變量和方法參數綁定在一起。

範例見《[spring]26 詳解@PathVariable,@RequestParam,@ResponseBody...》

A.5.1、URI template和正則表達式

Sometimes you need more precision in defining URI template variables. Consider the URL

"/spring-web/spring-web-3.0.5.jar".

有時候我們需要根據精確的定義一個URI template變量,例如,/spring-web/spring-web-3.0.5.jar。

@RequestMapping支持在URI template變量中使用正則表達式,語法爲:{varName:regex}。varName表示變量名稱,regex表示正則表達式。

舉例說明

針對/spring-web/spring-web-3.0.5.jar,我們可以這樣定義

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}.{extension:\\.[a-z]}")

public void handle(@PathVariable String version, @PathVariable String extension) {}

A.5.1、URI和*

@RequestMapping也支持*,如,/example/*.do。(不多解釋了)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章