What is `@RequestMapping` does?

发布时间:2024年01月15日

SpringMVC框架中,@RequestMapping 用于映射HTTP请求控制器类控制器类中方法
这个注解可以应用在类级别方法级别上。

使用样例

包含路径变量和HTTP方法:

@Controller
@RequestMapping("/api/v1")
public class MyApiController {

    @GetMapping("/users/{userId}")
    public ResponseEntity<User> getUser(@PathVariable("userId") Long id) {
        User user = userService.findById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(user);
    }

    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody User newUser) {
        User createdUser = userService.createUser(newUser);
        return ResponseEntity.created(URI.create("/api/v1/users/" + createdUser.getId())).body(createdUser);
    }

    @PutMapping("/users/{userId}")
    public ResponseEntity<User> updateUser(@PathVariable("userId") Long id, @RequestBody User updatedUser) {
        // 更新用户逻辑...
        return ResponseEntity.ok(updatedUser);
    }

    @DeleteMapping("/users/{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable("userId") Long id) {
        userService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

结合路径变量、请求参数和查询参数:

@Controller
@RequestMapping("/orders")
public class OrderController {

    @GetMapping("/{id}")
    public String getOrderDetails(@PathVariable("id") Long orderId,
                                 @RequestParam(name = "includeHistory", required = false, defaultValue = "false") boolean includeHistory) {
        // 获取订单详情以及根据请求参数决定是否包含历史记录...
        return "order-details";
    }
}

包含请求参数和header:

@Controller
@RequestMapping("/search")
public class SearchController {

    @GetMapping
    public String search(@RequestParam(value = "q", required = false, defaultValue = "") String query,
                         @RequestHeader(value = "X-Search-Preferences", required = false) String preferences) {
        // 搜索逻辑,基于query参数和header中的偏好信息...
        return "search-results";
    }
}

使用Ant风格路径匹配:

@Controller
@RequestMapping("/documents/**")
public class DocumentController {

    @GetMapping
    public String listDocuments() {
        // 列出所有文档逻辑...
        return "document-list";
    }

    @GetMapping("/{docId}")
    public String viewDocument(@PathVariable("docId") String docId) {
        // 查看特定文档逻辑...
        return "document-view";
    }
}

处理不同请求头和媒体类型的请求:

@Controller
@RequestMapping("/api")
public class MediaTypeController {

    @GetMapping(path = "/data", produces = "application/json")
    public MyData getJsonData() {
        // 返回JSON格式的数据...
        return new MyData();
    }

    @GetMapping(path = "/data", produces = "application/xml")
    public MyData getXmlData() {
        // 返回XML格式的数据...
        return new MyData();
    }
    
    @PostMapping(path = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        // 处理文件上传逻辑...
        return ResponseEntity.ok("File uploaded successfully");
    }
}

文章来源:https://blog.csdn.net/weixin_37646636/article/details/135598599
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。