Spring Web Annotations – Spring Web注释

最后修改: 2018年 6月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll explore Spring Web annotations from the org.springframework.web.bind.annotation package.

在本教程中,我们将探讨来自org.springframework.web.bind.annotation包的Spring Web注释。

2. @RequestMapping

2.@RequestMapping

Simply put, @RequestMapping marks request handler methods inside @Controller classes; it can be configured using:

简单地说,@RequestMapping @Controller类中标记请求处理方法;它可以使用配置。

  • path, or its aliases, name, and value: which URL the method is mapped to
  • method: compatible HTTP methods
  • params: filters requests based on presence, absence, or value of HTTP parameters
  • headers: filters requests based on presence, absence, or value of HTTP headers
  • consumes: which media types the method can consume in the HTTP request body
  • produces: which media types the method can produce in the HTTP response body

Here’s a quick example of what that looks like:

下面是一个快速的例子,说明这看起来像什么。

@Controller
class VehicleController {

    @RequestMapping(value = "/vehicles/home", method = RequestMethod.GET)
    String home() {
        return "home";
    }
}

We can provide default settings for all handler methods in a @Controller class if we apply this annotation on the class level. The only exception is the URL which Spring won’t override with method level settings but appends the two path parts.

如果我们在类的层面上应用这个注解,我们可以为@Controller类中的所有处理方法提供默认设置。唯一的例外是URL,Spring不会用方法级别的设置来覆盖,而是附加上两个路径部分。

For example, the following configuration has the same effect as the one above:

例如,下面的配置与上面的配置具有相同的效果。

@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
class VehicleController {

    @RequestMapping("/home")
    String home() {
        return "home";
    }
}

Moreover, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping are different variants of @RequestMapping with the HTTP method already set to GET, POST, PUT, DELETE, and PATCH respectively.

此外,@GetMapping@PostMapping@PutMapping@DeleteMapping@PatchMapping@RequestMapping的不同变体,HTTP方法已经分别设置为GET、POST、PUT、DELETE和PATCH。

These are available since Spring 4.3 release.

这些都是自Spring 4.3发布以来可用的。

3. @RequestBody

3.@RequestBody

Let’s move on to @RequestBody – which maps the body of the HTTP request to an object:

让我们来看看@RequestBody – 它将HTTP请求的正文映射到一个对象

@PostMapping("/save")
void saveVehicle(@RequestBody Vehicle vehicle) {
    // ...
}

The deserialization is automatic and depends on the content type of the request.

反序列化是自动的,取决于请求的内容类型。

4. @PathVariable

4.@PathVariable

Next, let’s talk about @PathVariable.

接下来,让我们谈谈@PathVariable

This annotation indicates that a method argument is bound to a URI template variable. We can specify the URI template with the @RequestMapping annotation and bind a method argument to one of the template parts with @PathVariable.

这个注解表明,方法参数被绑定到URI模板变量上。我们可以用@RequestMapping注解指定URI模板,并用@PathVariable将方法参数绑定到模板的某个部分。

We can achieve this with the name or its alias, the value argument:

我们可以通过name或其别名value参数来实现。

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable("id") long id) {
    // ...
}

If the name of the part in the template matches the name of the method argument, we don’t have to specify it in the annotation:

如果模板中的部分名称与方法参数的名称一致,我们就不必在注释中指定它。

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable long id) {
    // ...
}

Moreover, we can mark a path variable optional by setting the argument required to false:

此外,我们可以通过将参数required设为false来标记一个路径变量为可选。

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable(required = false) long id) {
    // ...
}

5. @RequestParam

5.@RequestParam

We use @RequestParam for accessing HTTP request parameters:

我们使用@RequestParam访问HTTP请求参数

@RequestMapping
Vehicle getVehicleByParam(@RequestParam("id") long id) {
    // ...
}

It has the same configuration options as the @PathVariable annotation.

它的配置选项与@PathVariable注解相同。

In addition to those settings, with @RequestParam we can specify an injected value when Spring finds no or empty value in the request. To achieve this, we have to set the defaultValue argument.

除了这些设置,通过@RequestParam,我们可以在Spring发现请求中没有值或空值时指定一个注入的值。为了实现这一点,我们必须设置defaultValue参数。

Providing a default value implicitly sets required to false:

提供一个默认值,隐含地将required设置为false:

@RequestMapping("/buy")
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
    // ...
}

Besides parameters, there are other HTTP request parts we can access: cookies and headers. We can access them with the annotations @CookieValue and @RequestHeader respectively.

除了参数,还有其他我们可以访问的HTTP请求部分:cookie和头文件。我们可以分别用注解@CookieValue@RequestHeader访问它们。

We can configure them the same way as @RequestParam.

我们可以用与@RequestParam相同的方式配置它们。

6. Response Handling Annotations

6.响应处理注释

In the next sections, we will see the most common annotations to manipulate HTTP responses in Spring MVC.

在接下来的章节中,我们将看到在Spring MVC中操作HTTP响应的最常用注解。

6.1. @ResponseBody

6.1.@ResponseBody

If we mark a request handler method with @ResponseBody, Spring treats the result of the method as the response itself:

如果我们用@ResponseBody标记一个请求处理方法, Spring将该方法的结果视为响应本身

@ResponseBody
@RequestMapping("/hello")
String hello() {
    return "Hello World!";
}

If we annotate a @Controller class with this annotation, all request handler methods will use it.

如果我们用这个注解来注解一个@Controller类,所有的请求处理方法都会使用它。

6.2. @ExceptionHandler

6.2.@ExceptionHandler

With this annotation, we can declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions.

通过这个注解,我们可以声明一个自定义错误处理方法。当请求处理方法抛出任何指定的异常时,Spring会调用这个方法。

The caught exception can be passed to the method as an argument:

被捕获的异常可以作为一个参数传递给方法。

@ExceptionHandler(IllegalArgumentException.class)
void onIllegalArgumentException(IllegalArgumentException exception) {
    // ...
}

6.3. @ResponseStatus

6.3.@ResponseStatus

We can specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument.

如果我们用这个注解来注解一个请求处理方法,我们可以指定响应的期望的HTTP状态。我们可以用code参数或其别名value参数声明状态代码。

Also, we can provide a reason using the reason argument.

另外,我们可以使用reason参数提供一个理由。

We also can use it along with @ExceptionHandler:

我们也可以把它和@ExceptionHandler一起使用。

@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
void onIllegalArgumentException(IllegalArgumentException exception) {
    // ...
}

For more information about HTTP response status, please visit this article.

关于HTTP响应状态的更多信息,请访问这篇文章

7. Other Web Annotations

7.其他网络注释

Some annotations don’t manage HTTP requests or responses directly. In the next sections, we’ll introduce the most common ones.

有些注解并不直接管理HTTP请求或响应。在接下来的章节中,我们将介绍最常见的那些。

7.1. @Controller

7.1. @Controller

We can define a Spring MVC controller with @Controller. For more information, please visit our article about Spring Bean Annotations.

我们可以用@Controller定义一个Spring MVC控制器。欲了解更多信息,请访问我们关于Spring Bean注释的文章

7.2. @RestController

7.2.@RestController

The @RestController combines @Controller and @ResponseBody.

@RestController 结合了@Controller@ResponseBody

Therefore, the following declarations are equivalent:

因此,下面的声明是等同的。

@Controller
@ResponseBody
class VehicleRestController {
    // ...
}
@RestController
class VehicleRestController {
    // ...
}

7.3. @ModelAttribute

7.3.@ModelAttribute

With this annotation we can access elements that are already in the model of an MVC @Controller, by providing the model key:

通过这个注解,我们可以访问已经在MVC @Controller的模型中的元素,通过提供模型密钥。

@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicleInModel) {
    // ...
}

Like with @PathVariable and @RequestParam, we don’t have to specify the model key if the argument has the same name:

@PathVariable@RequestParam一样,如果参数有相同的名字,我们就不必指定模型键。

@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute Vehicle vehicle) {
    // ...
}

Besides, @ModelAttribute has another use: if we annotate a method with it, Spring will automatically add the method’s return value to the model:

此外,@ModelAttribute还有另一个用途:如果我们用它来注解一个方法,Spring将自动地将该方法的返回值添加到模型中

@ModelAttribute("vehicle")
Vehicle getVehicle() {
    // ...
}

Like before, we don’t have to specify the model key, Spring uses the method’s name by default:

像以前一样,我们不需要指定模型键,Spring默认使用方法的名称。

@ModelAttribute
Vehicle vehicle() {
    // ...
}

Before Spring calls a request handler method, it invokes all @ModelAttribute annotated methods in the class.

在Spring调用一个请求处理方法之前,它会调用类中所有@ModelAttribute注解的方法。

More information about @ModelAttribute can be found in this article.

关于@ModelAttribute的更多信息可以在这篇文章中找到

7.4. @CrossOrigin

7.4.@CrossOrigin

@CrossOrigin enables cross-domain communication for the annotated request handler methods:

@CrossOrigin 为注释的请求处理方法启用跨域通信

@CrossOrigin
@RequestMapping("/hello")
String hello() {
    return "Hello World!";
}

If we mark a class with it, it applies to all request handler methods in it.

如果我们用它来标记一个类,它就适用于其中的所有请求处理方法。

We can fine-tune CORS behavior with this annotation’s arguments.

我们可以通过这个注解的参数来微调CORS行为。

For more details, please visit this article.

欲了解更多详情,请访问本文

8. Conclusion

8.结语

In this article, we saw how we can handle HTTP requests and responses with Spring MVC.

在这篇文章中,我们看到了如何用Spring MVC处理HTTP请求和响应。

As usual, the examples are available over on GitHub.

像往常一样,这些例子可以在GitHub上找到over

Next »

Spring Boot Annotations

« Previous

Spring Core Annotations