Explain the annotations commonly used in spring MVC 4

Source: Internet
Author: User
Tags html form

Spring has introduced annotations in programming starting with version 2.5, and users can use @requestmapping, @RequestParam, @ModelAttribute, and so on. Up to now, although the spring version has undergone a great change, but the characteristics of the annotation has been continued, and continue to expand, so that the vast number of developers of the hands of the more relaxed, this is inseparable from the powerful role of annotation, Today, let's take a look at the annotations commonly used in spring MVC 4.


1. @Controller


    controller controller is a behavior that provides access to the application through the Service interface definition, which interprets the user's input, Convert it into a model and then try to present it to the user. spring MVC uses @Controller to define the controller, It also allows automatic detection of components defined under the Classpath and autoenrollment. For automatic detection to take effect, you need to introduce spring-context under the XML header file:

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "     xmlns:p= "http://www.springframework.org/schema/p"     xmlns:context= "http// Www.springframework.org/schema/context "    xsi:schemalocation="          http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context        http:// Www.springframework.org/schema/context/spring-context.xsd ">    <context: Component-scan base-package= "Org.springframework.samples.petclinic.web"/>    <! -- ... --></beans>


2. @RequestMapping


We can @RequestMapping annotations to map URLs like "/favsoft" to the entire class or to a particular processing method. In general, class-level annotations map a specific request path to a form controller, whereas method-level annotations simply map to a specific HTTP method request ("GET", "POST", and so on) or an HTTP request parameter.


@Controller @requestmapping ("/favsoft") public class annotationcontroller {@RequestMapping (method =requestmethod.get) Public string get () {return  "";} @RequestMapping (value= "/getname",  method = requestmethod.get)     public  string getname (String username)  {        return  username;    } @RequestMapping (value= "/{day}",  method=requestmethod.get) public  string getday (date day) {Dateformat df = new simpledateformat ("Yyyy-MM-dd") ; Return df.format (day);} @RequestMapping (value= "/adduser",  method=requestmethod.get) Public string addfavuser (@Validated  favuser favuser,bindingresult result) {if (Result.haserrors ()) {return  "FavUser";} Favuserservice.addfavuser (Favuser);return  "Redirect:/favlist";} @RequestMapping ("/test") @ResponseBodypublic  string test () {return  "AA";}} 


@RequestMapping can act at the class level or at the method level. When it is defined at the class level, it indicates that the controller handles all requests that are mapped to the/favsoft path. The method property can be used in @RequestMapping to mark the type of methods it accepts, and if you do not specify a method type, you can use the HTTP Get/post method to request data, but once you specify the method type, you can only use that type to get the data.


@RequestMapping can use @Validated with Bindingresult to validate input parameters and return different views, respectively, in case of validation passing and failure.


@RequestMapping support for accessing URLs using URI templates. A URI template resembles a URL-like string, consisting of one or more variable names, which becomes a URI when the variables have values.


3. @PathVariable


In spring MVC, you can use @PathVariable annotation method parameters and bind them to the value of a URI template variable. As shown in the following code:


String Findowner (string, model model) {Favuser favuser = Favuserservice.findfavuser (); Model.addattribute (;}


The URI template "Favusers/{favuserid}" specifies the name of the variable Favuserid, and when the controller processes the request, the Favuserid value is set to the URI. For example, when there is a request like "Favusers/favccxx", the value of Favuserid is favccxx.


@PathVariable can have multiple annotations, like this:

@RequestMapping (value= "/owners/{ownerid}/pets/{petid}", method=requestmethod.get) public String Findpet (@    Pathvariable string ownerid, @PathVariable string petid, model model) {owner owner = Ownerservice.findowner (ownerid);    Pet pet = Owner.getpet (Petid);    Model.addattribute ("Pet", pet); return "Displaypet";}

The arguments in the @PathVariable can be any simple type, such as int, long, date, and so on. Spring will automatically convert it to the appropriate type or throw a Typemismatchexception exception. Of course, we can also register to support additional data types.


If @pathvariable uses map<string, string> type parameters, the map is populated with all URI template variables.


@PathVariable supports the use of regular expressions, which determines its super-powerful properties, which can be used in a path template using placeholders, you can set specific prefix matching, suffix matching and other custom formats.


@pathvariable also supports matrix variables, because there is not much to use in real-world scenarios, this is not described in detail, the need for children's shoes Please check the official website documentation.


4. @RequestParam


@RequestParam bind the requested parameter to a parameter in the method, as shown in the following code. In fact, even if you do not configure this parameter, annotations will use this parameter by default. If you want to customize the specified parameters, set the Required property of @requestparam to False (for example, @requestparam (value= "id", Required=false)).


5. @RequestBody


@RequestBody means that the method parameter should be bound to the HTTP request body.


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


If you think @requestbody is inferior to @requestparam, we can use Httpmessageconverter to transfer the body of the request to the method parameter, Httmessageconverser HTTP request messages are converted between object objects, but generally do not. It turns out that @RequestBody have a greater advantage over @requestparam when building a rest architecture.



6. @ResponseBody


@ResponseBody, similar to @requestbody, is the function of entering the return type directly into the HTTP response body. @ResponseBody are often used when outputting data in JSON format, see Code:


@RequestMapping (value = "/something", method = Requestmethod.put) @ResponseBodypublic String HelloWorld () {return ' Hell O World ";}


7. @RestController

we often see that some controllers implement the rest API to serve only Json,xml or other custom types of content . @RestController used to create a rest type of controller, with the @controller type. @RestController is a type that avoids repeating the @requestmapping and @responsebody you write.


@RestController

public class Favrestfulcontroller {


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

public string GetUserName (@RequestParam (value= "name") string name) {

return name;

}

}


8. httpentity


Httpentity can also access the request and response headers in addition to the request and response responses, as follows:


9. @ModelAttribute

@ModelAttribute can act on a method or method parameter, and when it acts on a method, the purpose of marking the method is to add one or more model attributes. This method supports the same parameter types as @requestmapping, but does not map directly to requests. The @modelattribute method in the controller is called before the @requestmapping method call, as shown in the following example:

@ModelAttributepublic account AddAccount (@RequestParam String number) {return accountmanager.findaccount (number);} @ModelAttributepublic void Populatemodel (@RequestParam String number, model model) {Model.addattribute (Accountmanager        . Findaccount (number)); Add More ...}


@ModelAttribute method is used to populate the model with attributes such as populating a drop-down list, pet type, or retrieving a command object such as an account (used to render data on an HTML form).


@ModelAttribute method has two styles: one is to add the Stealth property and return it. The other is that the method accepts a model and adds any number of model attributes. The user can choose the corresponding style according to their own needs.


@ModelAttribute function on the method parameter


When @modelattribute is acting on a method parameter, it indicates that the parameter can be retrieved in the method model. If the parameter is not in the current model, the parameter is first instantiated and then added to the model. Once the parameter is in the model, the field of the parameter should be populated with all request parameter matching names. This is an important data binding mechanism in spring MVC, which eliminates the time to parse each form field separately.


@ModelAttribute is a very common. the method of retrieving properties from the database, which is stored by using the request @sessionattributes. In some cases, it is convenient to retrieve properties from URI template variables and type converters.


The advent of annotations ended the era of XML configuration files flying in the sky, which made the program more readable, configurable and flexible. Of course, there are those who say that annotations are not as clear as the configuration file, and that individuals feel that the so-called structure should be a uniform specification rather than a stack of file structures. This is like object-oriented and structure-oriented, can you say that object-oriented logic is not clear?



This article is from the "Dust Wind with the Sky" blog, please be sure to keep this source http://favccxx.blog.51cto.com/2890523/1582185

Explain the annotations commonly used in spring MVC 4

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.