1. Power node _ Power node. 2

  • 2020-09-16 07:28:36
  • OfStack

Spring has introduced annotations in programming since version 2.5. Users can use @RequestMapping, @RequestParam, @ModelAttribute and similar annotations. So far, Spring has changed a lot, but the annotations feature has been extended and continued to make life easier for developers. Thanks to Annotation's powerful features, today we'll take a look at some of the most commonly used annotations in Spring MVC 4.

1. @Controller

The Controller controller is a behavior that provides access to an application defined through a service interface, interprets the user's input, converts it into a model, and then presents the attempt to the user. Spring MVC USES @Controller to define the controller, which also allows automatic detection and registration of components defined under the classpath. If you want the automatic detection to take effect, you need to introduce spring-ES22en under 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 use the @RequestMapping annotation to map URL like "/favsoft" to an entire class or to a specific handler. Generally, class-level annotations map a specific request path to a form controller, while methoder-level annotations simply map to a specific HTTP method request (" GET ", "POST", etc.) or 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")
  @ResponseBody
  public String test(){
    return "aa";
  }
   
}

@RequestMapping can be applied at the class level as well as the method level. When it is defined at the class level, indicate that the controller handles all requests that are mapped to the /favsoft path. You can use the method attribute in @RequestMapping to mark the accepted method type. 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 get data using that type.

@RequestMapping can use @Validated and BindingResult to jointly validate the input parameters and return different views in case of verification pass and failure.

@ES58en supports access to URL using the URI template. The URI template is an ES62en-like string consisting of one or more variable names that become URI when these variables have values.

3. @PathVariable

In Spring MVC, you can annotate method parameters using @PathVariable and bind them to the value of the URI template variable. The following code is shown:


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

The URI template "favusers/{favUserId}" specifies the variable name favUserId. When the controller handles this request, the value of favUserId is set to 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 @PathVariable can be of any simple type, such as int, long, Date, and so on. Spring automatically converts it to the appropriate type or throws an TypeMismatchException exception. Of course, we can also register to support additional data types.

If @PathVariable USES Map < String, String > Type, Map fills all URI template variables.

PathVariable supports the use of regular expressions, which makes it super powerful. It can use placeholders in path templates, and can set specific prefix matching, suffix matching, and other custom formats.

PathVariable also supports matrix variables, as few of them are used in real situations, so I won't introduce them in detail. If you need children's shoes, please check the documentation on the official website.

4. @RequestParam

@RequestParam binds the requested parameter to the parameter in the method, as shown in the code below. In fact, annotations will use this parameter by default even if it is not configured. If you want to customize the parameters, set the required attribute of @RequestParam to false (e.g. @RequestParam (value="id",required=false)).

5. @RequestBody

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


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

If you feel that @RequestBody is not as good as @ES150en, you can use HttpMessageConverter to transfer request's body to method parameters. HttMessageConverser converts HTTP request messages between Object objects, but this is generally not done. It turns out that @ES157en has a bigger advantage over @ES159en when it comes to building the REST architecture.

6. @ResponseBody

@ResponseBody is similar to @RequestBody in that it is used to enter the return type directly into HTTP response body. When @ES172en outputs data in JSON format, it is often used. The code is shown in the following figure:


@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() {  return "Hello World";
}

7. @RestController

We often see controllers that implement API for REST, only for JSON, XML or some other custom type of content, @RestController for creating REST controllers, and @ES187en. @RestController is one such type that prevents you from repeatedly writing @RequestMapping and @ResponseBody.


@RestController
public class FavRestfulController {
 
@RequestMapping(value="/getUserName",method=RequestMethod.POST)
public String getUserName(@RequestParam(value="name") String name){
return name;
}
}

8. HttpEntity

In addition to getting the request request and response response, HttpEntity also has access to the request and response headers, as shown below:


@RequestMapping("/something")public ResponseEntity<String> handle(HttpEntity<byte[]> 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<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

9. @ModelAttribute

ModelAttribute can be applied to a method or method parameter, and when it is applied to a method, indicates that the purpose of the method is to add one or more model attributes (model attributes). This method supports parameter types similar to @RequestMapping1, but does not map directly to requests. The @ModelAttribute method in the controller is called before the @RequestMapping method is called, 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 ...
}

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

The @ModelAttribute method comes in two flavors: One is to add a cloaking attribute and return it. The other is that the method takes one model and adds an arbitrary number of model attributes. Users can choose the corresponding style according to their own needs.

ModelAttribute applies to method parameters

When @ModelAttribute is applied to a method parameter, it indicates that the parameter can be retrieved in the method model. If the parameter is not in the current model, it is instantiated and then added to the model. 1 Once the parameter is present in the model, the field for the parameter should be populated with all the names that the request parameter matches. This is an important data binding mechanism in Spring MVC, which saves the time of parsing each form field individually.

@ES238en is a very common way to retrieve attributes from a database, using @SessionAttributes to request storage using request. In some cases, attributes can be easily retrieved through URI template variables and type converters.


Related articles: