[@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。(不多解释了)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值