Spring MVC common annotations

Source: Internet
Author: User

Spring MVC common annotations

A Controller is a behavior defined through a service interface that provides access to an application. It interprets user input, converts it into a model, and then tries to present it to the user. Spring MVC uses @ Controller to define the Controller. It also allows automatic detection of components defined in the class path and automatic registration. If you want to automatically check for effectiveness, You need to introduce spring-context under the XML header file:

<CODE class=" hljs xml"><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="&#13;&#10;        http://www.springframework.org/schema/beans&#13;&#10;        http://www.springframework.org/schema/beans/spring-beans.xsd&#13;&#10;        http://www.springframework.org/schema/context&#13;&#10;        http://www.springframework.org/schema/context/spring-context.xsd">     <!--{cke_protected}{C}%3C!%2D%2D%20...%20%2D%2D%3E--></beans></CODE>
2. @ RequestMapping we can @ RequestMapping annotation map URLs like "/favsoft" to the entire class or specific processing methods. Generally, annotation at the class level maps a specific request path to a form controller, while annotation at the method level only maps 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 be applied at the class level or method level. When it is defined at the class level, it indicates that all requests processed by the controller are mapped to the/favsoft path. @ RequestMapping: The method attribute can be used to mark the method type it accepts. If the method type is not specified, you can use the http get/POST method to request data. However, once the method type is specified, you can only use this type to obtain data. @ RequestMapping: You can use @ Validated and BindingResult to verify the input parameters. Different views are returned when the verification passes or fails. @ RequestMapping supports URL access using URI templates. The URI template is a URL-like string consisting of one or more variable names. When these variables have values, they become Uris.

@ PathVariable

In Spring MVC, you can use the @ PathVariable annotation method parameter and bind it to the value of the URI template variable. The following code is used:

 String findOwner( String , Model model) {    FavUser favUser = favUserService.findFavUser();    model.addAttribute(     ;}

The URI template "favusers/{favUserId}" specifies the variable name favUserId. When the controller processes this request, the value of favUserId is set to URI. For example, if there is a request like "favusers/favccxx", the value of favUserId is favccxx.

@ PathVariable can have multiple annotations, as shown below: @ 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 ";}
@ PathVariable parameters can be of any simple type, such as int, long, Date, and so on. Spring automatically converts it to an appropriate type or throws a TypeMismatchException. Of course, we can also register to support additional data types. If @ PathVariable uses a Map-type parameter, Map is filled in all URI template variables. @ PathVariable supports regular expressions, which determines its super-strong attributes. It can use placeholders in the path template and set custom formats such as prefix matching and suffix matching. @ PathVariable also supports matrix variables, because there are not many practical use cases, which will not be described in detail. For more information about shoes, see the documentation on the official website. 4. @ RequestParam binds the request parameters to the parameters in the method, as shown in the following code. In fact, the annotation uses this parameter by default even if this parameter is not configured. If you want to customize the specified parameter, set the required attribute of @ RequestParam to false (for example, @ RequestParam (value = "id", required = false )). 5. @ RequestBody indicates 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 writer) throws IOException {    writer.write(body);}

If you think that @ RequestBody is not as good as @ RequestParam, you can use HttpMessageConverter to transfer the request body to the method parameter. HttMessageConverser converts the HTTP request message between Object objects, however, this is generally not the case. It turns out that @ RequestBody has a greater advantage in building a REST architecture than @ RequestParam.

@ ResponseBody

@ ResponseBody is similar to @ RequestBody. It is used to directly input the return type to the HTTP response body. @ ResponseBody is often used when outputting data in JSON format. For the code, see:

@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() {    return "Hello World";}
7. @ RestController: we often see some controllers that implement REST APIs. They only serve JSON, XML, or other custom types. @ RestController is used to create a REST controller, and @ Controller. @ RestController is such a type, it avoids repeated write @ RequestMapping and @ ResponseBody.
@RestControllerpublic class FavRestfulController {@RequestMapping(value="/getUserName",method=RequestMethod.POST)public String getUserName(@RequestParam(value="name") String name){return name;}}
8. HttpEntityHttpEntity can access the request and response Headers in addition to the request and response, as shown below:
@RequestMapping("/something")public ResponseEntity handle(HttpEntity requestEntity) throws UnsupportedEncodingException {    String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));    byte[] requestBody = requestEntity.getBody();    // do something with request header and body    HttpHeaders responseHeaders = new HttpHeaders();    responseHeaders.set("MyResponseHeader", "MyValue");    return new ResponseEntity("Hello World", responseHeaders, HttpStatus.CREATED);}
9. @ ModelAttribute can be used on methods or method parameters. When it is used on methods, it indicates that the purpose of the method is to add one or more model attributes (model attributes ). This method supports the same parameter type as @ RequestMapping, but cannot be directly mapped to a request. The @ ModelAttribute method in the controller is called before the @ RequestMapping method is called, for 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 ...}
The @ ModelAttribute method is used to fill attributes in the model, such as filling the drop-down list, pet type, or retrieving a command object such as an account (used to render data on an HTML form ). The @ ModelAttribute method has two styles: add an invisible attribute and return it. Another method is to accept a model and add any number of model attributes. You can select a style based on your needs. @ ModelAttribute acts on the method parameter. When @ ModelAttribute acts on the method parameter, it indicates that this parameter can be retrieved in the method model. If this parameter is not in the current model, it is first instantiated and then added to the model. Once this parameter is included in the model, the field of this parameter should be filled with names matching all request parameters. This is an important data binding mechanism in Spring MVC, which saves time for parsing each form field separately. @ ModelAttribute is a common method for retrieving attributes from a database. It uses @ SessionAttributes to store requests. In some cases, you can easily retrieve attributes using URI template variables and Type converters.

Spring3.0 introduced RESTful architecture style support (supported by @ PathVariable annotation and some other features), and introduced more annotation support:
@ CookieValue: The cookie data is bound to the method parameter of the processing method of the processor function;
@ RequestHeader: Bind the Request header (header) data to the method parameter of the processing method of the processor function;
@ RequestBody: Binding of the Request body (type conversion through HttpMessageConverter );
@ ResponseBody: The Return Value of the processing method of the processor function as the response body (type conversion through HttpMessageConverter );
@ ResponseStatus: Define the processing method of the processor function/the status code and cause returned by the exception processor;
@ ExceptionHandler: Annotation-type declarative exception processor;
@ PathVariable: The template variable in the request URI is bound to the method parameter of the processing method of the processor function, so as to support the RESTful architecture. The RESTful Java Web implementation will be introduced in detail later.

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.