[@Controller]2 detailed @requestmapping

Source: Internet
Author: User
Tags class definition locale

A, @RequestMapping

Org.springframework.web.bind.annotation.RequestMapping

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

@RequestMapping Note that it maps Web requests to specific processor classes and/or processor methods. It supports servlet and portlet environments and is defined in the same way in both environments.

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

Note, the @requestmapping defined on the method only allows narrowing of the mapping scope of the @requestmapping defined on the class, if defined on the class. In a servlet scenario, an HTTP path requires a unique mapping to a specified processor bean, other mapping parameters, and a valid declaration of conditions. In the Portlet case,

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

The @requestmapping annotation method for the processor method is very flexible. It may have several types

A.1, @RequestMapping type

Class level (Type-level), where the annotation definition is above the class definition.

Method Level (Method-level), where the annotation definition is above the method definition.

Give an example to explain

@Controller

@RequestMapping ("/A")

Public class Helloworldcontroller {

@RequestMapping ("/helloworld")

Public String HelloWorld (model model) {

Model.addattribute ("message", "Hello world!");

return "HelloWorld";

}

}

@RequestMapping ("/A") is a class level (Class-level), @RequestMapping ("/helloworld") is a method level (Method-level). The example is to map the request address/a/helloworld to the HelloWorld processor.

properties for A.2, @RequestMapping

a.2.1, Value

The primary mapping expressed by this annotation.

The main mapping is expressed through 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 the supported within the primary mapping expressed to the type level.

In the servlet environment, the mapping path (for example,/mypath.do) also supports any style (e.g.,/mypath/*.do). The relative path in the method level requires a class-level master path support.

@RequestMapping ("/a") is equivalent to @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.

Reduces the scope of the primary mapping through the method of the HTTP request. Get, POST, head, OPTIONS, put, DELETE, TRACE.

Supported at the type level as so as at the ' method level!

Support is defined at the class level or at the method level.

@RequestMapping (value= "/b", Method=requestmethod.post)

a.2.3, params

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

Reduces the scope of the primary mapping by mapping the requested parameters.

Same format for no environment:a sequence of "myparam=myvalue" style expressions, with a request only mapped if each suc H parameter is found to have the given value. Expressions can is negated by using the "!=" operator, as in "Myparam!=myvalue". The "Myparam" style expressions are also supported, with such parameters has to is present in the request (allowed to have Any value). Finally, the "!myparam" style expressions indicate that the specified parameter was not supposed to being present in the request.

In any environment, a "myparam=myvalue" style expression is executed only if the request has such a parameter map. Negation can be expressed through the "!=" operator, such as "Myparam!=myvalue". The "Myparam" style expression also supports, mainly in the request, regardless of the value of the parameter. An expression of "!myparam" indicates that the specified parameter cannot appear in the request.

Supported at the type level as so as at the ' method level!

Support is defined at the class level or at the method level.

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

a.2.4, headers

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

Reduces the scope of the primary mapping by the requested header.

Same format for no environment:a sequence of "my-header=myvalue" style expressions, with a request only mapped if each s Uch header is found to have the given value. Expressions can is negated by using the "!=" operator, as in "My-header!=myvalue". "My-header" style expressions are also supported, with such headers has to is present in the request (allowed to have a NY value). Finally, "! My-header "style expressions indicate that specified Header isn't supposed to being present in the request.

In any environment, a "my-header=myvalue" style expression is executed only if the request has such headers. Negation can be expressed through the "!=" operator, such as "My-header!=myvalue". The "My-header" style expression also supports the presence of the Header in the request, regardless of the value. "! My-header expression indicates that the specified Header cannot appear in the request.

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

also support (*), for example,

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

return types supported by A.3 and related methods

The following return types are supported for handler methods:

The return type of the following processor method (the method @requestmapping annotated) is supported:

a.3.1, Modelandview

A Modelandview Object (Servlet MVC or Portlet MVC), with the model implicitly enriched with command objects and the result S of Modelattribute Annotated reference data accessor methods.

Modelandview (servlet or portlet) that suppresses the result of the Command object and the @ modelattribute annotation.

Give an example to explain

@RequestMapping ("/hello.do")

Public Modelandview HelloWorld () {

Modelandview mv=New Modelandview ();

Mv.setviewname ("HelloWorld");

Mv.addobject ("AttributeName", "AttributeValue");

return MV;

}

The Modelandview constructor allows you to specify the name of the page you return, or you can specify the page name by using the Setviewname () method, and use AddObject () to set the value that you want to return, AddObject () methods with several different parameters. You can default and specify the name of the returned object. Call the AddObject () method to set the value to a class attribute named Modelmap, Modelmap is a subclass of Linkedhashmap, see class.

a.3.2, Model

A model object, with the view name implicitly determined through a requesttoviewnametranslator and the model implicitly EN riched with command objects and the results of Modelattribute annotated reference data accessor.

Returns a model object to represent the models, while the view name uses Requesttoviewnametranslator to convert the request to the view name.

Give an example to explain

@RequestMapping ("/helloworld.do")

Public Model HelloWorld () {

Model model=New extendedmodelmap ();

Model.addattribute ("AttributeName", "attributeNameValue2");

return model;

}

Here the model of a implementation extendedmodelmap to represent the Model,requesttoviewnametranslator request "/helloworld.do" converted to the view name HelloWorld. If the request is/a/b.form, the view name is 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 .

Returns a Map object to represent the model, whereas the view name uses Requesttoviewnametranslator to convert the request to the view name.

Give an example to explain

@RequestMapping ("/helloworld.do")

Public Map<string, string> HelloWorld () {

map<string, string> map = new hashmap<string, string> ();

Map.put ("AttributeName", "Attributenamevalue");

return map;

}

Here, map is used to represent model,requesttoviewnametranslator to convert the request "/helloworld.do" to the view name HelloWorld. If the request is/a/b.form, the view name is a/b.

a.3.4, View

A View object, with the model implicitly determined through command objects and Modelattribute annotated data ac Cessor methods. The handler method could also programmatically enrich the model by declaring a model argument (the "* Above").

a.3.5, String

A String value which is interpreted as view name, with the model implicitly determined through command objects and Modelat Tribute annotated reference data accessor methods. The handler method could also programmatically enrich the model by declaring a modelmap argument.

Returns a Map object to represent the view name, and the method used in the processor can also represent model by declaring a modelmap parameter.

Give an example to explain

@RequestMapping ("/helloworld.do")

Public String HelloWorld (Modelmap model) {

Model.addattribute ("AttributeName", "attributeNameValue3");

return "HelloWorld";

}

The string "HelloWorld" returned here represents the view name, and the Modelmap type's argument represents model. You can also define parameters as model types.

a.3.6, @ResponseBody

@ResponseBody Annotated methods for access to the Servlet response HTTP contents. The return value is converted to the response stream using a message converters.

A method is annotated with @responsebody, which means that the method responds directly to HTTP content.

For details, see 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 is converted to the response stream using a message converters.

a.3.8, void

Void if the method handles the response itself (by writing the response content directly, declaring a argument of type Se Rvletresponse/httpservletresponse/renderresponse for this purpose) or if the view name is supposed to be implicitly de Termined through a requesttoviewnametranslator (not declaring a response argument to the handler method signature; Plicable in a Servlet environment).

Returns the null void representation method to handle the response itself by declaring a servletresponse or httpservletresponse or renderresponse type parameter to directly output the response content. The second is to convert a request to a view name through Requesttoviewnametranslator, which does not have to declare a response parameter in the processing method, but it can be used in a servlet environment.

Give an example to explain

@RequestMapping ("/helloworld.do")

Public void HelloWorld (Modelmap model) {

Model.addattribute ("AttributeName", "attributeNameValue3");

}

This is the second of the methods mentioned above, which converts the request "/helloworld.do" to the view name HelloWorld. As with a string, you can declare a MODELMAP parameter to represent model.

a.3.9, other return type

Any of the other return type would be considered as a single is exposed to the view, using the attribute name SPE Cified through Modelattribute at the "method level" (or the default attribute name based on the return type ' s class name oth Erwise). The model is implicitly enriched with command objects and the results of Modelattribute annotated data reference Ssor methods.

parameter types supported by A.4 and related methods

a.4.1, request or response

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

Request or Response object (Servlet). For example, ServletRequest or 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 a argument is never null.

Session object (Servlet), HttpSession. This type of argument it forces a related session to exist. So this parameter will never be empty.

a.4.3, WebRequest or Nativewebrequest

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

Generic request parameter Access as a request/session attribute access, without ties to the native Servlet/portlet A Pi.

WebRequest or Nativewebrequest. It allows access to general request parameters like access to request or session attributes, without the need to use the 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 is used for the locale of the current request, and this locale is determined by the specified localeresolver.

a.4.5, InputStream, or 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 or reader is used to access the requested content.

a.4.6, outputstream or 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 or writer is used to generate response content.

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.

This parameter @PathVariable annotation is used to access the URI template variable.

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 annotation parameters are used to access specific servlet request parameters. The value of the parameter is converted to the declared parameter type.

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.

The @RequestHeader annotation parameter is used to access the HTTP headers of a particular servlet request. The value of the parameter is converted to the declared parameter type.

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.

The @RequestBody annotation parameter is used to access the HTTP request content. Httpmessageconverters converts the value of a parameter to a declared parameter type.

a.4.12, @RequestPart

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

The @RequestPart annotation parameter is used to access the contents of the "Multipart/form-data" request section.

a.4.13, httpentity<?>

Httpentity<?> parameters for access to the Servlet request HTTP headers and contents. The request stream is converted to the entity body using httpmessageconverters.

The httpentity<?> parameter is used to access the HTTP headers and contents of the servlet request. The request stream will be httpmessageconverters into the contents of the entity.

a.4.13, MAP, model or Modelmap

Java.util.map/org.springframework.ui.model/

Org.springframework.ui.ModelMap for enriching the implicit model this is exposed to the Web view.

The MAP, model, or modelmap is used to enrich the implied model that is provided to the Web view.

a.4.14, redirectattributes org.springframework.web.servlet.mvc.support.RedirectAttributes to specify the Exact set of attributes to (a) Redirect and also to add flash attributes (attributes stored temporarily on th e 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 redirect View.

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 Customizab Le type conversion, depending on @InitBinder methods and/or the Handleradapter configuration. The Webbindinginitializer property on Requestmappinghandleradapter. Such command objects along with their validation results would be exposed as model attributes by default, using the command Class class name-e.g. Model "OrderAddress" for a Command object of type "Some.package.OrderAddress". The Modelattribute annotation can is used on a method argument to customize the model attribute name used.

Binding a Command object or Form object to the properties of a bean (through setters) or directly to a field, using a custom type converter, depending on the @initbinder method and Handleradapter configuration (reference, Requestmappinghandleradapter webbindinginitializer attribute). By default, such command objects, along with their validation results, are provided externally as a model property. @ModelAttribute note can be used to declare a method parameter from defining the use of a model property name.

a.4.16, errors or Bindingresult

Org.springframework.validation.errors/org.springframework.validation.bindingresult validation results for a Preceding command or Form object.

Errors or bindingresult used in conjunction with 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 this have been indicated by the @SessionAttributes annotation at the handler type level.

Sessionstatus state processing is used to mark the form processing as completed, triggering the scavenging session property, which is defined by the @sessionattributes annotation at the processor class level.

a.4.18, Uricomponentsbuilder

Org.springframework.web.util.UriComponentsBuilder a builder for preparing a URL relative to the current request ' s host, PO RT, Scheme, context path, and the literal part of the servlet mapping.

 

a.5, Uri template (URI template)

The URI refers to the @requestmapping ("URI"), which is the Value property of the requestmapping.

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

URI Template The selected part of the @requestmapping method access URL.

The URI template rule is defined in http://code.google.com/p/uri-templates/

A URI template that can contain multiple variable names (these variable names are enclosed in {}). For example, a URI template is: Http://www.example.com/users/{userid} It contains a userId variable. Then we need to use @pathvariable to bind the URI template variable with the method parameter.

examples See "[spring]26 detailed @pathvariable, @RequestParam, @ResponseBody ..."

a.5.1, URI template, and regular expressions

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

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

Sometimes we need to define a URI template variable according to the exact definition, for example,/spring-web/spring-web-3.0.5.jar.

@RequestMapping supports the use of regular expressions in URI template variables, the syntax is: {Varname:regex}. VarName represents the variable name, and the regex represents the regular expression.

Give an example to explain

For/spring-web/spring-web-3.0.5.jar, we can define this.

@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, URIs and *

@RequestMapping also supports *, such as/example/*.do. (not much explained).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.