Spring @RequestMapping
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何在经典的 Spring Web 应用程序中使用 @RequestMapping 注解。该注解用于将 Web 请求映射到请求处理类中的处理方法。
Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。
@RequestMapping
@RequestMapping 用于将 Web 请求映射到请求处理类中的处理方法。将 Web 请求映射到处理方法的过程也称为路由。
@RequestMapping 具有以下特化:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
该注解可用于类级别和方法级别。如果在两个级别上都使用,请求路径将合并。
Spring @RequestMapping 示例
在下面的示例中,我们将演示 @RequestMapping
注解的用法。
pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ ├───config │ │ │ MyWebInitializer.java │ │ │ WebConfig.java │ │ └───controller │ │ MyController.java │ │ TestController.java │ └───resources │ index.html │ logback.xml └───test └───java
这是项目结构。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>RequestMappingEx</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <spring-version>5.3.23</spring-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.49.v20220914</version> </plugin> </plugins> </build> </project>
在 pom.xml
中,我们有项目依赖项。
<?xml version="1.0" encoding="UTF-8"?> <configuration> <logger name="org.springframework" level="ERROR"/> <logger name="com.zetcode" level="INFO"/> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n </Pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="consoleAppender" /> </root> </configuration>
这是 logback.xml
配置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home page</title> </head> <body> <p> This is home page. </p> </body> </html>
这是一个主页。
package com.zetcode.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @Configuration public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
MyWebInitializer
初始化 Spring Web 应用程序。它包含一个配置类:WebConfig
。
package com.zetcode.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.zetcode"}) public class WebConfig implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
WebConfig
配置 Spring Web 应用程序。
package com.zetcode.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.time.LocalTime; @RestController public class MyController { @RequestMapping(value = "/") public String home() { return "This is Home page"; } @RequestMapping(value = "/about", method = RequestMethod.POST) public String about() { return "This is About page; POST request"; } @RequestMapping(value = "/fresh", method = {RequestMethod.POST, RequestMethod.GET}) public String fresh() { return "This is Fresh page; GET/POST request"; } @RequestMapping(value = "/todo", consumes = "text/plain") public String todo() { return "This is Todo page; text/plain content type"; } @RequestMapping(value = "/time", params = { "info=time" }) public String showTime() { var now = LocalTime.now(); return String.format("%s", now.toString()); } }
MyController
使用 @RequestMapping
定义了各种路由。
@RequestMapping(value = "/") public String home() { return "This is Home page"; }
使用 value
选项,我们将 /
请求路径映射到 home
处理方法。如果未明确指定,则默认请求方法为 GET。value
是 path
选项的别名。
@RequestMapping(value = "/about", method = RequestMethod.POST) public String about() { return "This is About page; POST request"; }
使用 method
选项,我们可以将处理程序映射限制为具有 /about
路径的 POST 请求。
@RequestMapping(value = "/fresh", method = {RequestMethod.POST, RequestMethod.GET}) public String fresh() { return "This is Fresh page; GET/POST request"; }
此方法可以接受 GET 和 POST 请求。
@RequestMapping(value = "/todo", consumes = "text/plain") public String todo() { return "This is Todo page; text/plain content type"; }
使用 consumes
选项,我们可以将映射限制为具有已定义内容类型的请求。
@RequestMapping(value = "/time", params = { "info=time" }) public String showTime() { var now = LocalTime.now(); return String.format("%s", now.toString()); }
使用 params
选项,我们将映射限制为带有 /time
路径和 info=time
请求参数的 GET 请求。
package com.zetcode.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value="/test") public class TestController { @RequestMapping(value = "/info") public String info() { return "This is info page"; } @RequestMapping(path="*.do") public String somePage() { return "This is some page"; } }
TestController
还有另外两个映射。
@RestController @RequestMapping(value="/test") public class TestController {
我们也可以将 @RequestMapping
放在类上。然后将路径与方法路径合并。
@RequestMapping(value = "/info") public String info() { return "This is info page"; }
此处理程序映射到 /test/info
路径。
@RequestMapping(path="*.do") public String somePage() { return "This is some page"; }
path
选项等同于 value
。它可以接受 Ant 风格的 URL 映射。
$ mvn jetty:run
我们运行 Jetty 服务器。
$ curl localhost:8080 This is Home page
我们使用 curl
工具生成一个请求到主页的 GET 请求。
$ curl -X POST localhost:8080/about This is About page; POST request
这是一个 POST 请求到 /about
路径。
$ curl -X POST localhost:8080/fresh This is Fresh page; GET/POST request $ curl -X GET localhost:8080/fresh This is Fresh page; GET/POST request
/fresh
页面同时接受 GET 和 POST 请求。
$ curl -d "info=time" localhost:8080/time 13:24:29.934670700
我们向 /time
页面发送一个带有参数的请求。
$ curl localhost:8080/test/info This is info page
类级别和方法级别的注解合并为 /test/info
路径。
$ curl localhost:8080/test/produce.do This is some page
最后是 Ant 风格的映射。
在本文中,我们使用 @RequestMapping
注解创建了各种路由。
作者
列出 所有 Spring 教程。