Spring MVC 4 Common annotation Rollup

Source: Internet
Author: User
Tags html form http request

The new architecture of the rest-style interface with spring boot, which has been around for almost 2 years without a massive use of spring MVC, and found that many new annotations have not been used, has taken a little time to learn and summarize, and Spring MVC is now a powerful feature. The development of the rest interface can be simplified by using a large number of annotations.

Spring has introduced annotations in programming from version 2.5, where users can use @requestmapping, @RequestParam, @ModelAttribute, and so on. So far, although the spring version has changed a lot, but the characteristics of the annotation has been continued, and expanding, so that the vast number of developers of the hands become more relaxed, this is inseparable from the powerful role of annotation, today we will look at spring MVC 4 of the commonly used annotation bar.

1. @Controller

The Controller controller is an act of providing access to an application defined through a service interface that interprets the user's input, converts it into a model, and then attempts to present it to the user. Spring MVC uses @Controller to define the controller, and it also allows automatic detection of components defined in the Classpath and autoenrollment. If you want 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=" 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 an entire class or to a specific processing method. In general, class-level annotations map specific request paths to form controllers, and method-level annotations are only mapped to a specific HTTP method request ("Get", "POST", etc.) or HTTP request parameters.

@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")
    @ResponseBody public
    String test () {return
        "AA";
    }
     
}

@RequestMapping can work either at the class level or at the method level. When it is defined at the class level, it is indicated that the controller handles all requests that are mapped to the/favsoft path. @RequestMapping You can use the method property to mark the type of methods that 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 a method type, you can only use that type to get the data.

@RequestMapping can use @Validated and bindingresult to validate input parameters and return different views when validation passes and fails.

@RequestMapping supports accessing URLs using URI templates. A URI template is like a string of URLs, consisting of one or more variable names, and when these variables have a value, it becomes a URI.

3. @PathVariable

In spring MVC, you can use the @PathVariable annotation method parameter and bind it to the value of the 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 Favuserid value is favccxx.

@PathVariable can have multiple annotations, as follows:

@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 parameters in the @PathVariable can be any simple type, such as int, long, date, and so on. Spring automatically converts it to the appropriate type or throws 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 into all URI template variables.

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

@PathVariable also support matrix variables, because the real scene is not used much, this is not detailed, the need for children's shoes Please check the official website of the document.

4. @RequestParam

@RequestParam bind the requested parameter to an argument in the method, as shown in the following code. In fact, annotations use this parameter by default even if you do not configure this parameter. If you want to customize the specified parameters, set the @requestparam required property to False (such as @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 think @requestbody inferior @requestparam take advantage of hand, we can use Httpmessageconverter to transfer request body to method parameter, Httmessageconverser will HTTP request messages are converted between object objects, but they are not normally done. As it turns out, @RequestBody have a greater advantage than @requestparam when building a rest architecture.

6. @ResponseBody

@ResponseBody is similar to @requestbody, which is to enter the return type directly into the HTTP response body. @ResponseBody when outputting JSON-formatted data, the code is often used, as shown in the following figure:

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

7. @RestController

We often see some controllers that implement rest APIs only to serve Json,xml or other custom type content, @RestController used to create rest-type controllers, and @controller types. @RestController is such a type that it avoids the repetition of writing @requestmapping and @responsebody.

@RestController public
class Favrestfulcontroller {
 
@RequestMapping (value= "/getusername"), method= requestmethod.post) Public
String GetUserName (The @RequestParam (value= "name") string name) {return
   name;
}
}


8. Httpentity

In addition to obtaining request requests and response responses, httpentity can access the request and response headers as follows:

@RequestMapping ("/something") public responseentity<string> handle (httpentity<byte[]> requestentity) Throws Unsupportedencodingexception {
    String requestheader = Requestentity.getheaders (). GetFirst (" Myrequestheader "));    byte[] Requestbody = Requestentity.getbody ();    Do something with the request header and body

    httpheaders responseheaders = new Httpheaders ();
    Responseheaders.set ("Myresponseheader", "myvalue");    Return to New responseentity<string> ("Hello World", Responseheaders, httpstatus.created);
}

9. @ModelAttribute

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

@ModelAttribute Public Account
AddAccount (@RequestParam String number) {return
    Accountmanager.findaccount ( number);
}

@ModelAttribute public
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, a 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 attribute and return it. The other is that the method accepts a model and adds any number of model properties. Users can choose the corresponding style according to their own needs.

@ModelAttribute function on the method parameters

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 instantiated and then added to the model. Once the parameter is in the model, the field of the parameter should populate the names that match all the request parameters. This is an important data binding mechanism in spring MVC, which eliminates the time it took to parse each form field individually.

@ModelAttribute is a very common method of retrieving properties from a database, which is stored using request requests via @sessionattributes. In some cases, you can easily retrieve properties from the URI template variable and the type converter.

@Cacheable and @cacheflush

• @Cacheable: Declaring a method's return value should be cached. For example: @Cacheable (modelid = "testcaching")

• @CacheFlush: Declaring a method is a trigger that empties the cache. For example: @CacheFlush (modelid = "testcaching")

• description

To work with the cache processor, refer to: http://hanqunfeng.iteye.com/blog/603719

SPRING3.0 does not provide support for caching, but after 3.1, you can refer to: Spring3.1 cache annotation

@Resource

• For example

@Resource
Private DataSource DataSource; Inject the bean named ' DataSource '

• OR

@Resource (name= "DataSource")
@Resource (Type=datasource.class)

• description

@Resource by default, by the name of the bean, and if not found, the type is searched.
This is similar to the @autowired

If the name attribute is not explicitly specified for @Resource annotation, if it is annotated in the Beanfactory type, ApplicationContext type, Resourceloader type, Applicationeventpublisher type, Messagesource type, then Spring automatically injects instances of these implementation classes without additional action. The Name property does not need to be specified (or specified as "") at this time, or the injection fails;

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.