Home > Java > javaTutorial > body text

Introducing commonly used annotation methods in spring mvc

巴扎黑
Release: 2017-09-08 09:47:46
Original
1492 people have browsed it

This article mainly introduces the common annotations of spring mvc, and introduces similar annotations such as @RequestMapping, @RequestParam, @ModelAttribute and so on in detail. Those who are interested can learn more

Spring starts from version 2.5 To introduce annotations in programming, users can use similar annotations such as @RequestMapping, @RequestParam, @ModelAttribute, etc. So far, although the Spring version has undergone great changes, the features of annotations have been continued and continuously expanded, making the hands of the majority of developers easier. This is inseparable from the power of Annotation. Function, today we will take a look at the annotations commonly used in Spring MVC 4.

1. @Controller

Controller controller is a behavior defined through the service interface that provides access to the application. It interprets the user's takes input, converts it into a model and then renders the view to the user. Spring MVC uses @Controller to define controllers, which also allows components defined on the classpath to be automatically detected and automatically registered. 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="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>
Copy after login

2. @RequestMapping

We can use the @RequestMapping annotation to map a URL like "/favsoft" to the entire class or a specific processing method. Generally speaking, class-level annotations map a specific request path to the form controller, while method-level annotations simply map 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";
  }
   
}
Copy after login

@RequestMapping can act on both the class level and the method level. When it is defined at the class level, it indicates that all requests handled by this controller are mapped to the /favsoft path. You can use the method attribute in @RequestMapping to mark the method types 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 that type to obtain data.

@RequestMapping You can use @Validated and BindingResult to jointly verify the input parameters. If the verification passes or fails, different views will be returned respectively.

@RequestMapping supports using URI templates to access URLs. A URI template is a URL-like string consisting of one or more variable names. When these variables have values, it becomes a URI.

3. @PathVariable

In Spring MVC, you can use @PathVariable to annotate method parameters and bind them to URI template variables. Value. As shown in the following code:


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

URI template "favusers/{favUserId}" specifies the name of the variable favUserId. When the controller processes this request, the value of favUserId will be 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 the following:


@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";
}
Copy after login

The parameters in @PathVariable can be any simple Types, such as int, long, Date, etc. Spring will automatically convert it to the appropriate type or throw a TypeMismatchException. Of course, we can also register to support additional data types.

If @PathVariable uses Map type parameters, Map will be filled in all URI template variables.

@PathVariable supports the use of regular expressions, which determines its super powerful properties. It can use placeholders in path templates, and can set specific prefix matching, suffix matching, etc. Define the format.

@PathVariable also supports matrix variables. Because they are not used much in real-life scenarios, I will not introduce them in detail. If you need children's shoes, please check the official website's documentation.

4. @RequestParam

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

5. @RequestBody

##@RequestBody means that the method parameters 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);
}
Copy after login

If you feel that @RequestBody is not as good as @RequestParam, we can use HttpMessageConverter to transfer the body of the request to the method parameters. HttMessageConverser will exchange HTTP request messages between Object objects. conversion, but this is generally not done. It turns out that @RequestBody has greater advantages than @RequestParam when building REST architecture.


6. @ResponseBody

@ResponseBody is similar to @RequestBody. Its function is to input the return type directly into the HTTP response body. @ResponseBody is often used when outputting data in JSON format. The code is shown below:


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

7. @RestController

我们经常见到一些控制器实现了REST的API,只为服务于JSON,XML或其它自定义的类型内容,@RestController用来创建REST类型的控制器,与@Controller类型。@RestController就是这样一种类型,它避免了你重复的写@RequestMapping与@ResponseBody。


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

8. HttpEntity

HttpEntity除了能获得request请求和response响应之外,它还能访问请求和响应头,如下所示:


@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);
}
Copy after login

9. @ModelAttribute

@ModelAttribute可以作用在方法或方法参数上,当它作用在方法上时,标明该方法的目的是添加一个或多个模型属性(model attributes)。该方法支持与@RequestMapping一样的参数类型,但并不能直接映射成请求。控制器中的@ModelAttribute方法会在@RequestMapping方法调用之前而调用,示例如下:


@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 ...
}
Copy after login

@ModelAttribute方法用来在model中填充属性,如填充下拉列表、宠物类型或检索一个命令对象比如账户(用来在HTML表单上呈现数据)。

@ModelAttribute方法有两种风格:一种是添加隐形属性并返回它。另一种是该方法接受一个模型并添加任意数量的模型属性。用户可以根据自己的需要选择对应的风格。

@ModelAttribute作用在方法参数上

当@ModelAttribute作用在方法参数上时,表明该参数可以在方法模型中检索到。如果该参数不在当前模型中,该参数先被实例化然后添加到模型中。一旦模型中有了该参数,该参数的字段应该填充所有请求参数匹配的名称中。这是Spring MVC中重要的数据绑定机制,它省去了单独解析每个表单字段的时间。

@ModelAttribute是一种很常见的从数据库中检索属性的方法,它通过@SessionAttributes使用request请求存储。在一些情况下,可以很方便的通过URI模板变量和类型转换器检索属性。

The above is the detailed content of Introducing commonly used annotation methods in spring mvc. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!