Spring @RequestMapping New Shortcut Annotations – Spring @RequestMapping 新的捷径注解

最后修改: 2017年 2月 6日

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

1. Overview

1.概述

Spring 4.3. introduced some very cool method-level composed annotations to smooth out the handling @RequestMapping in typical Spring MVC projects.

Spring 4.3。引入了一些非常酷的方法级组成的注解,以平滑处理@RequestMapping在典型的Spring MVC项目中的问题。

In this article, we will learn how to use them in an efficient way.

在这篇文章中,我们将学习如何以有效的方式使用它们。

2. New Annotations

2.新的注释

Typically, if we want to implement the URL handler using traditional @RequestMapping annotation, it would have been something like this:

通常,如果我们想用传统的@RequestMapping注解来实现URL处理程序,它应该是这样的。

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)

The new approach makes it possible to shorten this simply to:

新方法使之有可能简单地缩短为。

@GetMapping("/get/{id}")

Spring currently supports five types of inbuilt annotations for handling different types of incoming HTTP request methods which are GET, POST, PUT, DELETE and PATCH. These annotations are:

Spring目前支持五种内置注解,用于处理不同类型的传入HTTP请求方法,即GET、POST、PUT、DELETEPATCH。这些注解是。

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

From the naming convention we can see that each annotation is meant to handle respective incoming request method type, i.e. @GetMapping is used to handle GET type of request method, @PostMapping is used to handle POST type of request method, etc.

从命名规则中我们可以看到,每个注解都是为了处理各自传入的请求方法类型,即@GetMapping是用来处理GET类型的请求方法,@PostMapping是用来处理POST类型的请求方法,等等。

3. How It Works

3.它是如何工作的

All of the above annotations are already internally annotated with @RequestMapping and the respective value in the method element.

上述所有的注释都已经在内部用@RequestMappingmethod元素中的相应值进行了注释。

For example, if we’ll look at the source code of @GetMapping annotation, we can see that it’s already annotated with RequestMethod.GET in the following way:

例如,如果我们看一下@GetMapping注解的源代码,我们可以看到它已经用RequestMethod.GET注解了。

@Target({ java.lang.annotation.ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = { RequestMethod.GET })
public @interface GetMapping {
    // abstract codes
}

All the other annotations are created in the same way, i.e. @PostMapping is annotated with RequestMethod.POST, @PutMapping is annotated with RequestMethod.PUT, etc.

所有其他注解都以同样的方式创建,即@PostMapping被注解为RequestMethod.POST@PutMapping被注解为RequestMethod.PUT,等等。

The full source code of the annotations is available here.

注释的完整源代码可在这里获得。

4. Implementation

4.实施

Let’s try to use these annotations to build a quick REST application.

让我们尝试使用这些注解来构建一个快速的REST应用程序。

Please note that since we would use Maven to build the project and Spring MVC to create our application, we need to add necessary dependencies in the pom.xml:

请注意,由于我们将使用Maven构建项目,并使用Spring MVC创建我们的应用程序,我们需要在pom.xml中添加必要的依赖项:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

The latest version of spring-webmvc is available in the Central Maven Repository.

spring-webmvc的最新版本在Central Maven Repository中提供。

Now, we need to create the controller to map incoming request URL. Inside this controller, we would use all of these annotations one by one.

现在,我们需要创建一个控制器来映射传入的请求URL。在这个控制器中,我们将逐一使用所有这些注释。

4.1. @GetMapping

4.1.@GetMapping

@GetMapping("/get")
public @ResponseBody ResponseEntity<String> get() {
    return new ResponseEntity<String>("GET Response", HttpStatus.OK);
}
@GetMapping("/get/{id}")
public @ResponseBody ResponseEntity<String>
  getById(@PathVariable String id) {
    return new ResponseEntity<String>("GET Response : " 
      + id, HttpStatus.OK);
}

4.2. @PostMapping

4.2.@PostMapping

@PostMapping("/post")
public @ResponseBody ResponseEntity<String> post() {
    return new ResponseEntity<String>("POST Response", HttpStatus.OK);
}

4.3. @PutMapping

4.3.@PutMapping

@PutMapping("/put")
public @ResponseBody ResponseEntity<String> put() {
    return new ResponseEntity<String>("PUT Response", HttpStatus.OK);
}

4.4. @DeleteMapping

4.4.@DeleteMapping

@DeleteMapping("/delete")
public @ResponseBody ResponseEntity<String> delete() {
    return new ResponseEntity<String>("DELETE Response", HttpStatus.OK);
}

4.5. @PatchMapping

4.5.@PatchMapping

@PatchMapping("/patch")
public @ResponseBody ResponseEntity<String> patch() {
    return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
}

Points to note:

需要注意的事项:

  • We have used the necessary annotations to handle proper incoming HTTP methods with URI. For example, @GetMapping to handle “/get” URI, @PostMapping to handle “/post” URI and so on
  • Since we are making an REST-based application, we are returning a constant string (unique to each request type) with 200 response code to simplify the application. We have used Spring’s @ResponseBody annotation in this case.
  • If we had to handle any URL path variable, we can simply do it in much less way we used to do in case of using @RequestMapping.

5. Testing the Application

5.测试应用程序

To test the application we need to create a couple of test cases using JUnit. We would use SpringJUnit4ClassRunner to initiate the test class. We would create five different test cases to test each annotation and every handler we declared in the controller.

为了测试该应用程序,我们需要使用JUnit创建几个测试案例。我们将使用SpringJUnit4ClassRunner来启动测试类。我们将创建五个不同的测试用例来测试每个注解和我们在控制器中声明的每个处理器。

Let’s simple the example test case of @GetMapping:

让我们简单看看@GetMapping:的例子测试案例。

@Test 
public void giventUrl_whenGetRequest_thenFindGetResponse() 
  throws Exception {

    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
      .get("/get");

    ResultMatcher contentMatcher = MockMvcResultMatchers.content()
      .string("GET Response");

    this.mockMvc.perform(builder).andExpect(contentMatcher)
      .andExpect(MockMvcResultMatchers.status().isOk());

}

As we can see, we are expecting a constant string “GET Response“, once we hit the GET URL “/get”.

正如我们所看到的,我们期待一个常量字符串”GET Response“,一旦我们击中GET URL”/get”。

Now, let’s create the test case to test @PostMapping:

现在,让我们创建测试案例来测试@PostMapping

@Test 
public void givenUrl_whenPostRequest_thenFindPostResponse() 
  throws Exception {
    
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
      .post("/post");
	
    ResultMatcher contentMatcher = MockMvcResultMatchers.content()
      .string("POST Response");
	
    this.mockMvc.perform(builder).andExpect(contentMatcher)
      .andExpect(MockMvcResultMatchers.status().isOk());
	
}

In the same way, we created the rest of the test cases to test all of the HTTP methods.

以同样的方式,我们创建了其余的测试案例来测试所有的HTTP方法。

Alternatively, we can always use any common REST client, for example, PostMan, RESTClient etc, to test our application. In that case, we need to be a little careful to choose correct HTTP method type while using the rest client. Otherwise, it would throw 405 error status.

另外,我们也可以使用任何常见的REST客户端,例如PostMan、RESTClient等,来测试我们的应用程序。在这种情况下,我们在使用休息客户端时需要稍微小心,选择正确的HTTP方法类型。否则,它将抛出405错误状态。

6. Conclusion

6.结论

In this article, we had a quick introduction to the different types of @RequestMapping shortcuts for quick web development using traditional Spring MVC framework. We can utilize these quick shortcuts to create a clean code base.

在这篇文章中,我们快速介绍了不同类型的@RequestMapping快捷方式,以便使用传统的Spring MVC框架进行快速Web开发。我们可以利用这些快速捷径来创建一个干净的代码库。

Like always, you can find the source code for this tutorial in the Github project.

像往常一样,你可以在Github项目中找到本教程的源代码。