跳转至

Spring @RequestMapping教程

原文: 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注解的用法。

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           ├───config
│   │           │       MyWebInitializer.java
│   │           │       WebConfig.java
│   │           └───controller
│   │                   MyController.java
│   │                   TestController.java
│   └───resources
│           index.html
│           logback.xml
└───test
    └───java

这是项目结构。

pom.xml

<?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>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-version>5.1.3.RELEASE</spring-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</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>5.1.3.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.14.v20181114</version>
            </plugin>

        </plugins>
    </build>
</project>

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

resources/logback.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配置

resources/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

<p>
    This is home page.
</p>

</body>
</html>

这是一个主页。

com/zetcode/config/MyWebInitializer.java

package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FrameworkServlet;
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

com/zetcode/config/WebConfig.java

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 应用。

com/zetcode/controller/MyController.java

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。 valuepath选项的别名。

@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 请求的映射。

com/zetcode/controller/TestController.java

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

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

$ 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

最后是蚂蚁风格的映射。

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

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


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组