@ResponseBody是Spring MVC中的注解,用于标识Controller类中的方法返回值是响应体内容,而不是视图名称。

使用@ResponseBody注解时,Spring MVC将会使用消息转换器将方法返回值转换为JSON、XML或其他格式的响应体内容,并将其写入响应中。如果方法返回类型为String,则直接将其作为响应体内容返回。

示例:

@RestController
public class UserController {
    
    @GetMapping("/users/{id}")
    @ResponseBody
    public User getUser(@PathVariable Long id) {
        // 返回用户信息
        User user = userService.getUserById(id);
        return user;
    }
    
    @PostMapping("/users")
    @ResponseBody
    public User createUser(@RequestBody User user) {
        // 创建用户
        User createdUser = userService.createUser(user);
        return createdUser;
    }
    
}

在上面的示例中,使用@ResponseBody注解标识方法返回值为响应体内容。在getUser方法中,返回类型为User对象,Spring MVC将会使用消息转换器将其转换为JSON格式的响应体内容;在createUser方法中,使用@RequestBody注解接收请求体中的JSON数据,并将其转换为User对象,然后再将创建成功的User对象作为响应体内容返回

responsebody的用法

原文地址: https://www.cveoy.top/t/topic/fqvN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录