原文: http://zetcode.com/spring/requestmapping/

Spring @RequestMapping教程显示了如何在 Spring Web 应用中使用@RequestMapping注解。 注解用于将 Web 请求映射到请求处理类中的处理器方法上。

Spring 是用于创建企业应用的流行 Java 应用框架。

@RequestMapping

@RequestMapping用于将 Web 请求映射到请求处理类中的处理器方法上。 将 Web 请求映射到处理器方法的过程也称为路由。

@RequestMapping具有以下特化:

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

注释可以在类和方法级别上使用。 如果在两个级别上都使用,则将请求路径合并。

Spring @RequestMapping示例

在下面的示例中,我们演示@RequestMapping注解的用法。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. ├───config
  8. MyWebInitializer.java
  9. WebConfig.java
  10. └───controller
  11. MyController.java
  12. TestController.java
  13. └───resources
  14. index.html
  15. logback.xml
  16. └───test
  17. └───java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>RequestMappingEx</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. <spring-version>5.1.3.RELEASE</spring-version>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>ch.qos.logback</groupId>
  20. <artifactId>logback-classic</artifactId>
  21. <version>1.2.3</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>javax.servlet</groupId>
  25. <artifactId>javax.servlet-api</artifactId>
  26. <version>4.0.1</version>
  27. <scope>provided</scope>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-webmvc</artifactId>
  32. <version>5.1.3.RELEASE</version>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.apache.maven.plugins</groupId>
  39. <artifactId>maven-war-plugin</artifactId>
  40. <version>3.2.2</version>
  41. </plugin>
  42. <plugin>
  43. <groupId>org.eclipse.jetty</groupId>
  44. <artifactId>jetty-maven-plugin</artifactId>
  45. <version>9.4.14.v20181114</version>
  46. </plugin>
  47. </plugins>
  48. </build>
  49. </project>

pom.xml中,我们具有项目依赖项。

resources/logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <logger name="org.springframework" level="ERROR"/>
  4. <logger name="com.zetcode" level="INFO"/>
  5. <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
  6. <encoder>
  7. <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
  8. </Pattern>
  9. </encoder>
  10. </appender>
  11. <root>
  12. <level value="INFO" />
  13. <appender-ref ref="consoleAppender" />
  14. </root>
  15. </configuration>

这是logback.xml配置

resources/index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Home page</title>
  6. </head>
  7. <body>
  8. <p>
  9. This is home page.
  10. </p>
  11. </body>
  12. </html>

这是一个主页。

com/zetcode/config/MyWebInitializer.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.context.WebApplicationContext;
  4. import org.springframework.web.servlet.DispatcherServlet;
  5. import org.springframework.web.servlet.FrameworkServlet;
  6. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  7. @Configuration
  8. public class MyWebInitializer extends
  9. AbstractAnnotationConfigDispatcherServletInitializer {
  10. @Override
  11. protected Class<?>[] getRootConfigClasses() {
  12. return null;
  13. }
  14. @Override
  15. protected Class<?>[] getServletConfigClasses() {
  16. return new Class[]{WebConfig.class};
  17. }
  18. @Override
  19. protected String[] getServletMappings() {
  20. return new String[]{"/"};
  21. }
  22. }

MyWebInitializer初始化 Spring Web 应用。 它包含一个配置类:WebConfig

com/zetcode/config/WebConfig.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  5. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  7. @Configuration
  8. @EnableWebMvc
  9. @ComponentScan(basePackages = {"com.zetcode"})
  10. public class WebConfig implements WebMvcConfigurer {
  11. @Override
  12. public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  13. configurer.enable();
  14. }
  15. }

WebConfig配置 Spring Web 应用。

com/zetcode/controller/MyController.java

  1. package com.zetcode.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RequestMethod;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import java.time.LocalTime;
  6. @RestController
  7. public class MyController {
  8. @RequestMapping(value = "/")
  9. public String home() {
  10. return "This is Home page";
  11. }
  12. @RequestMapping(value = "/about", method = RequestMethod.POST)
  13. public String about() {
  14. return "This is About page; POST request";
  15. }
  16. @RequestMapping(value = "/fresh", method = {RequestMethod.POST, RequestMethod.GET})
  17. public String fresh() {
  18. return "This is Fresh page; GET/POST request";
  19. }
  20. @RequestMapping(value = "/todo", consumes = "text/plain")
  21. public String todo() {
  22. return "This is Todo page; text/plain content type";
  23. }
  24. @RequestMapping(value = "/time", params = { "info=time" })
  25. public String showTime() {
  26. var now = LocalTime.now();
  27. return String.format("%s", now.toString());
  28. }
  29. }

MyController具有@RequestMapping的各种路由定义。

  1. @RequestMapping(value = "/")
  2. public String home() {
  3. return "This is Home page";
  4. }

使用value选项,我们将/请求路径映射到home()处理器方法。 如果未明确指定,则默认请求方法为 GET。 valuepath选项的别名。

  1. @RequestMapping(value = "/about", method = RequestMethod.POST)
  2. public String about() {
  3. return "This is About page; POST request";
  4. }

使用method选项,我们可以将处理器映射范围缩小到具有/about路径的 POST 请求。

  1. @RequestMapping(value = "/fresh", method = {RequestMethod.POST, RequestMethod.GET})
  2. public String fresh() {
  3. return "This is Fresh page; GET/POST request";
  4. }

此方法可以接受 GET 和 POST 请求。

  1. @RequestMapping(value = "/todo", consumes = "text/plain")
  2. public String todo() {
  3. return "This is Todo page; text/plain content type";
  4. }

使用consumes选项,我们可以将映射范围缩小到具有定义的内容类型的请求。

  1. @RequestMapping(value = "/time", params = { "info=time" })
  2. public String showTime() {
  3. var now = LocalTime.now();
  4. return String.format("%s", now.toString());
  5. }

使用params选项,我们可以缩小到/time路径和info=time请求参数的 GET 请求的映射。

com/zetcode/controller/TestController.java

  1. package com.zetcode.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. @RequestMapping(value="/test")
  6. public class TestController {
  7. @RequestMapping(value = "/info")
  8. public String info() {
  9. return "This is info page";
  10. }
  11. @RequestMapping(path="*.do")
  12. public String somePage() {
  13. return "This is some page";
  14. }
  15. }

TestController具有另外两个映射。

  1. @RestController
  2. @RequestMapping(value="/test")
  3. public class TestController {

我们也可以将@RequestMapping放在类上。 然后将路径与方法路径合并。

  1. @RequestMapping(value = "/info")
  2. public String info() {
  3. return "This is info page";
  4. }

该处理器映射到/test/info路径。

  1. @RequestMapping(path="*.do")
  2. public String somePage() {
  3. return "This is some page";
  4. }

path选项等效于value。 它可以接受 Ant 样式的 URL 映射。

  1. $ mvn jetty:run

我们运行 Jetty 服务器。

  1. $ curl localhost:8080
  2. This is Home page

我们使用curl工具向主页生成 GET 请求。

  1. $ curl -X POST localhost:8080/about
  2. This is About page; POST request

这是对/about路径的 POST 请求。

  1. $ curl -X POST localhost:8080/fresh
  2. This is Fresh page; GET/POST request
  3. $ curl -X GET localhost:8080/fresh
  4. This is Fresh page; GET/POST request

/fresh页面接受 GET 和 POST 请求。

  1. $ curl -d "info=time" localhost:8080/time
  2. 13:24:29.934670700

我们将带有参数的请求发送到/time页面。

  1. $ curl localhost:8080/test/info
  2. This is info page

类级别和方法级别的注解被组合到/test/info路径中。

  1. $ curl localhost:8080/test/produce.do
  2. This is some page

最后是蚂蚁风格的映射。

在本教程中,我们使用@RequestMapping注解创建了各种路径。

您可能也对这些相关教程感兴趣: Spring WebJars 教程Spring @GetMapping教程Spring DefaultServlet教程Spring Web 应用简介Java 教程