"SPRINGMVC" note-driven controller details

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Spring2.5 introduces annotation-based processor support, defining our processor classes through @controller and @requestmapping annotations. and provides a powerful set of annotations that require processor mapping Defaultannotationhandlermapping and processor adapter Annotationmethodhandleradapter to turn on support @controller and @requestmapping The processor for the annotation.


@Controller: Used to identify the processor class;

@RequestMapping: Mapping rules for request-to-processor functional methods;

@RequestParam: Bind the request parameter to the method parameter of the processor function processing method;

@ModelAttribute: The binding of the request parameter to the command object;

@InitBinder: Custom Data binding registration support for converting request parameters to the corresponding type of command object properties;
First, the View returns

1. Returns a String object

@RequestMapping (value = "/index")//relative to the root directory of the path public String test (Modelmap model) {Model.addattribute ("message", " Call Firstcontroller's Test method "); return" index ";//Specify the view path to which the page will jump}
Returns the name of the view directly, as a result:


2. Return Modelandview Object

@RequestMapping ("/index1") public Modelandview test2 () {Modelandview Modelandview = new Modelandview ();/// Modelandview.setview (New Redirectview ("index1")); Modelandview.setviewname ("index1");// Specifies the view path for the page to jump Modelandview.addobject ("message", "Call Firstcontroller's Test1 method");//second parameter: Specifies the parameters to be passed by the foreground, which can be taken in the foreground ${ Sp_ids}return Modelandview;}
Results:

which

Modelandview.setviewname ("index1");
Can also be written as:

Modelandview.setview (New Redirectview ("index1"));

Modelandview ()

This construction method constructs the Modelandview
cannot be used directly, no view is specified for it, and the corresponding model object is not bound. Of course, the model object is not required, but the view does have to be.
Examples constructed with this constructor are used to add view settings and Model objects later.
To Modelandview
There are two ways to set up view instances
A: Setviewname (String viewName) and Setview (view view). The former is using the view
Name, which uses a pre-constructed view object. One of the former is more commonly used. In fact, view is an interface, not a concrete class that can be constructed, and we can only get it by other means.
The instance of the view. For view
Name, which can be either the name of the JSP or the name defined by the tiles, depends on how the Viewnameresolver is used to understand the view name.
How to get an instance of view to study later.
and the corresponding how to give Modelandview
Instance setting model is more complex. There are three ways to use:
AddObject (Object Modelobject) AddObject (String modelname, Object modelobject) addallobjects (Map modelmap)
Two@RequestMapping

For various annotations, the first is of course "@Controller", indicating that a class is a Controller. The "@RequestMapping" request path mapping, if labeled at the class level of a controller, indicates that access to the method under such a path is accompanied by the path of its configuration, most commonly labeled on the method, indicating which specific method is used to accept processing of a request.

@RequestMapping parameter Description

Value defines the URL address of the request that handles the method. Method defines the type of HTTP method to handle, such as GET, POST, and so on. The params defines the parameters that must be included in the requested URL. Headers define the parameters that must be included in Request Headers

2.1 Intercept Path settings

(1) Methods of interception

@Controllerpublic class Firstcontroller {@RequestMapping (value = "/index")//the path to the root directory public String test (MODELMAP model {Model.addattribute ("message", "call the test method of Firstcontroller"); return "index";//Specify the view path of the page to jump}}
Indicates interception: Http://localhost:8080/SpringMVCLearningChapter2 /index1


(2) interception on a class

@Controller @requestmapping ("/user") public class Secondcontroller {@RequestMapping (value = "/index") public String test (Modelmap model) {Model.addattribute ("message", "call the test method of Secondcontroller"), return "index";//Specify the view path to which the page is to jump} @RequestMapping ("/ Index1 ") Public Modelandview test2 () {Modelandview Modelandview = new Modelandview ();///modelandview.setview (new Redirectview ("index1")); Modelandview.setviewname ("index1");//Specify the View path Modelandview.addobject ("message") to which the page will jump. "Call the Test1 method of Secondcontroller");//The second parameter: Specifies the parameters to be passed by the foreground, in which case the foreground can be ${sp_ids}return modelandview;}
Indicates interception: http://localhost:8080/SpringMVCLearningChapter2/User/index

and http://localhost:8080/SpringMVCLearningChapter2/user/index1

Block: root directory/user/index and root directory/user/index1


Request Mapping
    • Normal URL path mapping

@RequestMapping (value={"/login.do", "/user/login.do"}): Multiple URL paths can be mapped to the same processor 's function handling method.

    • URL Template Pattern Mapping

@RequestMapping (value= "/users/{userid}"): {XXX} placeholder, the requested URL can be "/users/123456" or "/USERS/ABCD".

@RequestMapping (value= "/users/{userid}/login.do"): This is also possible, the URL of the request can be "/users/123/login.do".

@RequestMapping (value= "/users/{userid}/channel/{channelid}"): This is also possible, the requested URL can be "/users/123/channel/456".

    • Ant-style URL path mapping

@RequestMapping (value= "/users/**"): Can Match "/USERS/ABC/ABC".

@RequestMapping (value= "/model"): Can Match "/model1" or "/modela", but does not match "/model" or "/modelaa";

@RequestMapping (value= "/model*"): Can Match "/modelabc" or "/model", but does not match "/MODELABC/ABC";

@RequestMapping (value= "/model/*"): Can Match "/MODEL/ABC", but does not match "/MODELABC";

@RequestMapping (value= "/model/**/{modelid}"): Can Match "/model/abc/abc/123" or "/model/123",

That is, ant style and URI template variable style can be mixed;

    • URL path mapping for regular expression styles

A URL path mapping that supports regular expression styles starting with Spring3.0, in the format {variable name: regular expression}

@RequestMapping (value= "/login/{userid://d+}.do"): Can match

"/login/123.do", but cannot match "/login/abc.do", so you can design more strict rules.

    • Combination use is a "or" relationship

Combinations such as @requestmapping (value={"/login.do", "/user/login.do"}) use the relationship that is or, that is, "/login.do" or

The "/user/login.do" request URL path can be mapped to the function handling method specified by @requestmapping.


2. param parameters

If you want to set the parameters passed to a page, you can write the following:

@Controller @requestmapping ("/third") public class Thirdcontroller {@RequestMapping (value = "/index", params= "name")// Required pass parameter name, after entering name in the browser, the controller will automatically pass the parameter to the Namepublic String test (modelmap model,string name) {Model.addattribute (" Message ", name); return" Index ";}}

Input Http://localhost:8080/SpringMVCLearningChapter2/third/index is inaccessible at this point:

Because it requires that you must pass a name parameter, you have to write this:

Of course, it is also possible to annotate the required parameters to the parameters of the method.

@RequestMapping (value = "/index")//required to pass the parameter name, the controller automatically passes the parameter to the Namepublic String test in test (Modelmap model,@) After the name is entered in the browser. Requestparam ("name") String name) {model.addattribute ("message", name); return "index";}

Effects and the same as above. At this time if still want to visit Http://localhost:8080/SpringMVCLearningChapter2/third/index, put Required=false plus

@RequestMapping (value = "/index") public string test (Modelmap model, @RequestParam (value= "name", Required=false) string Name) {Model.addattribute ("message", name); return "index";}

3. Method

@RequestMapping (value = "/index1", method = requestmethod.get,params= "name") public Modelandview test2 () {Modelandview Modelandview = new Modelandview ();///modelandview.setview (New Redirectview ("index1")); Modelandview.setviewname (" Index1 ");//Specify the view path of the page to jump Modelandview.addobject (" message "," Call Secondcontroller Test1 method ");//second parameter: Specifies the parameters to be passed by the foreground , in the foreground can be value ${sp_ids}return modelandview;}
Indicates that it can only be accessed via get, or post, to

method = Requestmethod.post

4. Head

@RequestMapping (Headers)
The headers function is also used to refine the mapping. The processing method is called only if the requested request Headers contains parameters that match the heanders value.
@RequestMapping (value = "/specify", headers = "accept=text/*")
Public String Specify () {
return "Example_specify_page";
}
The value of the Accept in the requested request Headers must match text/* (such as text/html) before the method is called.


Third, other commonly used annotations

The handler method parameter binds common annotations, which we divide into four categories according to the different contents of the request they process: (mainly on common types)

A, the processing Requet URI part (here refers to the URI template in variable, does not contain the QueryString part) the annotation: @PathVariable;

B, the processing of the request header section of the note: @RequestHeader, @CookieValue;

C, the processing of the request body part of the note: @RequestParam, @RequestBody;

D, processing attribute type is annotated: @SessionAttributes, @ModelAttribute;

1. @PathVariable

When using the @requestmapping URI template style mapping, which is/fourth/{num}, num can bind the value passed to the method by @Pathvariable annotations.

Example code:

@Controller @requestmapping ("/fourth/{num}") public class Fourthcontroller {@RequestMapping (value = "/index/{string}" public string test (Modelmap model, @PathVariable ("num") int num, @PathVariable ("string") string string) { Model.addattribute ("message", "num=" +string.valueof (num) + "  string=" +string); return "Index";}}
Browser input: Http://localhost:8080/SpringMVCLearningChapter2/fourth/1234/index/linbingwen


The above code binds the value of the variable num in the URI template and the value of string to the parameter of the method. If the variable names in the method parameter names and URI template that need to be bound are inconsistent, you need to specify the name in the URI template in @pathvariable ("num").

2. @RequestHeader, @CookieValue

@RequestHeader annotations, you can bind the value of the header portion of a request to a method parameter.

 @RequestMapping          (value = "/index", method = requestmethod.get) public string Gethello (@RequestHeader ("host") string hostName, @RequestHeader ("Accept") string Accepttype, @RequestHeader ("Accept-language") string AcceptLang, @R Equestheader ("accept-encoding") string Acceptenc, @RequestHeader ("Cache-control") string Cachecon, @Re Questheader ("Cookie") string Cookie, @RequestHeader ("User-agent") string useragent) {System.out.print      ln ("Host:" + hostName);      System.out.println ("Accept:" + accepttype);      System.out.println ("Accept Language:" + AcceptLang);      System.out.println ("Accept Encoding:" + Acceptenc);      System.out.println ("Cache-control:" + Cachecon);      System.out.println ("Cookie:" + cookie);         System.out.println ("user-agent:" + useragent);     Return "index"; }
@CookieValue can bind the value of the cookie in the request header to the parameters of the method.

If you have the following cookie values:

jsessionid=415a4ac178c59dace0b2c9ca727cdd84
Code for parameter binding:
@RequestMapping ("/displayheaderinfo.do") public void Displayheaderinfo (@CookieValue ("Jsessionid") String cookie)  {  //...}
That is, bind the value of Jsessionid to the parameter cookie.
3, @RequestParam, @RequestBody

@RequestParam

A) commonly used to deal with simple types of bindings, a String obtained by Request.getparameter () can be converted directly into a simple type case (string--> The conversion of a simple type is done by a converter configured by Conversionservice), because the parameter is obtained using the Request.getparameter () method, so you can handle the value of querystring in the Get mode, or you can handle the post mode The value of body data;

B) used to deal with Content-type: for application/x-www-form-urlencoded encoded content, submit the way get, POST;

C) The note has two properties: value, required, value specifies the ID name to pass in the value, and required is used to indicate whether the parameter must be bound;

@RequestBody

This annotation is often used to deal with Content-type: not application/x-www-form-urlencoded encoded content, such as Application/json, application/xml, etc.;

It is configured by using Handleradapter HttpMessageConverters to parse the post data body and then bind to the corresponding bean.

Because the configuration has formhttpmessageconverter, so can also be used to deal with application/x-www-form-urlencoded the content, processed results in a multivaluemap<string, string>, this situation in some special needs to use, See Formhttpmessageconverter API for details;

Example code:

@RequestMapping (value = "/something", method = requestmethod.put) public void handle (@RequestBody String body, Writer writ ER) throws IOException {  writer.write (body);}

4, @SessionAttributes, @ModelAttribute

@SessionAttributes:

This annotation is used to bind the value of the attribute object in the HttpSession, which is convenient for use in parameters in the method.

The annotation has value, types two attributes, and can specify the attribute object to use by name and type;

Example code:

@Controller @requestmapping ("/editpet.do") @SessionAttributes ("Pet") public class Editpetform {    //...}


@ModelAttribute

The note has two usages, one for the method and one for the parameter;

When used on a method: the model that needs to be queried from the background to bind the request before processing @requestmapping;

When used on parameters: used to bind the value of the corresponding name to the parameter bean of the annotation by name, and the value to be bound is derived from:

A) on the attribute object that is @SessionAttributes enabled;

B) @ModelAttribute for the model object specified on the method;

C) In either case, the new one needs to bind the Bean object, and then binds the value in the request to the bean in the same way as the name.


Sample code to @modelattribute on the method:

@ModelAttributepublic account AddAccount (@RequestParam String number) {    return Accountmanager.findaccount (number );}

The actual effect of this method is to put ("account" and account) in the model of the request object before invoking the @requestmapping method.


The @modelattribute sample code that is used on the parameter:

@RequestMapping (value= "/owners/{ownerid}/pets/{petid}/edit", method = requestmethod.post) public String Processsubmit (@ModelAttribute Pet Pet) {   }
The first query @SessionAttributes there is no bound pet object, if not the query @modelattribute method layer is bound to the Pet object, if not the value in the URI template is bound to the properties of the pet object by the corresponding name.


Iv. Supplementary explanation question: How is the parameter bound without a given note?

By analyzing source code discovery for Annotationmethodhandleradapter and Requestmappinghandleradapter, the parameters of the method are not given in the case of parameters:

To bind an object to a simple type: Call @requestparam to handle it.

To bind an object when complex type: Call @modelattribute to process.

The simple Type here refers to the primitive type of Java (boolean, int, etc.), primitive type Object (boolean, int, etc.), string, date, etc. conversionservice can directly convert the string into the target object type;

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka



"SPRINGMVC" note-driven controller detailed

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.