Spring中 @RequestMapping 注解的用法与示例

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Spring中 @RequestMapping 注解

Answer:

在 Spring 框架中,@RequestMapping 注解用于将 HTTP 请求映射到特定的处理方法上。它可以用于类级别和方法级别,允许开发者定义 URL 路径、HTTP 方法、请求参数、请求头等信息,以便更好地控制请求的路由。

基本用法

  1. 类级别的 @RequestMapping: 当在控制器类上使用 @RequestMapping 时,所有该类中的处理方法都会继承这个路径前缀。

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class MyController {
        
        @RequestMapping("/hello")
        public String hello() {
            return "Hello, World!";
        }
    }
    

    在这个例子中,访问 /api/hello 会调用 hello() 方法。

  2. 方法级别的 @RequestMapping: 可以在方法上使用 @RequestMapping 来定义特定的请求处理。

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MyController {
        
        @RequestMapping("/hello")
        public String hello() {
            return "Hello, World!";
        }
    
        @RequestMapping("/goodbye")
        public String goodbye() {
            return "Goodbye, World!";
        }
    }
    

    这里,/hello/goodbye 都会被映射到相应的方法。

HTTP 方法

可以通过 method 属性指定支持的 HTTP 方法,例如 GET、POST、PUT、DELETE 等。

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }

    @PostMapping("/hello")
    public String createHello(@RequestBody String message) {
        return "Created: " + message;
    }
}

在这个例子中,/api/hello 的 GET 请求会调用 hello() 方法,而 POST 请求会调用 createHello() 方法。

请求参数和请求头

可以使用 paramsheaders 属性来进一步限制请求的条件。

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping(value = "/hello", params = "name")
    public String hello(@RequestParam String name) {
        return "Hello, " + name + "!";
    }

    @GetMapping(value = "/hello", headers = "X-API-VERSION=1")
    public String helloV1() {
        return "Hello, World! Version 1";
    }
}

在这个例子中,只有当请求中包含 name 参数时,hello() 方法才会被调用,而 helloV1() 方法则需要请求头中包含 X-API-VERSION=1

总结

@RequestMapping 是 Spring 中非常强大的注解,能够帮助开发者灵活地处理 HTTP 请求。随着 Spring 版本的更新,Spring 还引入了更具体的注解,如 @GetMapping@PostMapping@PutMapping@DeleteMapping,这些注解是 @RequestMapping 的简化版本,提供了更清晰的语义。