欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > Spring_MVC 中的 JSON 数据处理与 REST 风格开发

Spring_MVC 中的 JSON 数据处理与 REST 风格开发

2025/4/28 10:16:39 来源:https://blog.csdn.net/2301_77129242/article/details/147548658  浏览:    关键词:Spring_MVC 中的 JSON 数据处理与 REST 风格开发

Spring_MVC 中的 JSON 数据处理与 REST 风格开发

一、JSON 格式参数

1. 格式布置

依赖导入

为了处理 JSON 数据,需要在项目中引入 Jackson 库,它是 Spring_MVC 默认使用的 JSON 处理工具。

<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.4</version>
</dependency>

配置类

在 Spring 配置类中启用 @EnableWebMvc 注解,以激活 Spring_MVC 的高级功能,包括 JSON 数据的自动处理。

@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class WebConfig {
}
  • @EnableWebMvc:启用 Spring_MVC 的高级功能,包括数据绑定、内容协商等。
  • @ComponentScan:指定 Spring 容器扫描的包路径,确保控制器类被正确加载。

2. JSON 数组格式

示例:接收 JSON 数组

使用 @RequestBody 注解可以接收客户端发送的 JSON 数组,并将其自动转换为 Java 对象。

@Controller
@RequestMapping("/json")
public class JsonController {@PostMapping("/so")@ResponseBodypublic String handleJsonArray(@RequestBody List<String> teachers) {System.out.println("Received teachers: " + teachers);return "{\"model\": \"springmvc\"}";}
}
  • @RequestBody:将请求体中的 JSON 数据绑定到方法参数。
  • List:接收一个字符串数组。

Postman 测试

在 Postman 中,可以将请求类型设置为 POST,并在请求体中输入 JSON 数组:

["Alice","Bob","Charlie"
]

3. JSON 引用类型

示例:接收 JSON 对象

Spring_MVC 可以自动将 JSON 对象转换为对应的 Java 类。

@PostMapping("/st")
@ResponseBody
public String handleJsonObject(@RequestBody Teacher teacher) {System.out.println("Received teacher: " + teacher.getName());return "{\"model\": \"springmvc\"}";
}
  • Teacher 类

    public class Teacher {private String name;private int age;// Getters and Setterspublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
    }
    

Postman 测试

在 Postman 中,发送以下 JSON 数据:

{"name": "Alice","age": 30
}

4. JSON 引用数组类型

示例:接收 JSON 对象数组
在这里插入图片描述

Spring_MVC 也可以处理 JSON 对象数组,并将其转换为 Java 对象列表。

@PostMapping("/sf")
@ResponseBody
public String handleJsonArrayObject(@RequestBody List<Teacher> teachers) {System.out.println("Received teachers: " + teachers);return "{\"model\": \"springmvc\"}";
}

Postman 测试

在 Postman 中,发送以下 JSON 数据:

[{"name": "itcsa","id": 123},{"name": "itcsass","id": 125}
]

5. 细节讲述

@RequestBody 与 @RequestParam 的区别

  • @RequestBody:用于接收请求体中的 JSON 数据,并将其反序列化为 Java 对象。
  • @RequestParam:用于接收 URL 参数或表单数据。

示例

@PostMapping("/example")
@ResponseBody
public String example(@RequestBody User user, @RequestParam String token) {System.out.println("User: " + user.getName());System.out.println("Token: " + token);return "{\"status\": \"success\"}";
}
  • @RequestBody User user:接收 JSON 数据并转换为 User 对象。
  • @RequestParam String token:接收 URL 参数 token

二、响应类型处理

1. 返回 JSP 页面

在 Spring_MVC 中,可以直接返回 JSP 页面的名称,而无需使用 @ResponseBody

@GetMapping("/save")
public String save() {return "index.jsp";
}
  • 返回的字符串是 JSP 页面的路径,Spring_MVC 会自动解析并渲染该页面。

2. 返回纯文本

使用 @ResponseBody 注解可以返回纯文本响应。

@GetMapping("/text")
@ResponseBody
public String text() {return "This is a plain text response.";
}
  • @ResponseBody:将方法的返回值直接作为响应体返回。

3. 返回 JSON 数据

@RequestMapping("/sv")
@ResponseBody
public student sv(){System.out.println("返回json数据类型");student student = new student();student.setId(123);student.setName("智能");return student;
}

在这里插入图片描述

是通过respnsebody进行设置的,设置返回类型转换为下面设置的student的类型

数组类型的json:

@RequestMapping("/sm")
@ResponseBody
public List<student> sm(){System.out.println("返回json数据引用类型");student student = new student();student.setId(123);student.setName("智能");student student1 = new student();student1.setName("王五");student1.setId(456);List<student> students = new ArrayList<>();students.add(student1);students.add(student);return students;
}

4、@ResponseBody

类型:方法注解

作用:设置当前控制器作为返回值

三、REST 风格开发

1. REST 原理

REST(Representational State Transfer,表现层状态转换)是一种软件架构风格,用于设计网络应用程序。它强调使用 HTTP 方法(GET、POST、PUT、DELETE 等)来操作资源。

在这里插入图片描述

2. REST 风格的使用规范

示例:CRUD 操作

@RestController
@RequestMapping("/api/users")
public class UserController {@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}@GetMapping("/{id}")public User getUserById(@PathVariable int id) {return userService.getUserById(id);}@PostMappingpublic User createUser(@RequestBody User user) {return userService.createUser(user);}@PutMapping("/{id}")public User updateUser(@PathVariable int id, @RequestBody User user) {return userService.updateUser(id, user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable int id) {userService.deleteUser(id);}
}
  • @RestController:标记控制器为 REST 风格。
  • @GetMapping@PostMapping@PutMapping@DeleteMapping:分别用于处理 GET、POST、PUT、DELETE 请求。

3. REST 风格的注解使用场景

在这里插入图片描述

4. REST 风格的简用用法

示例:使用 @RestController@RequestMapping

@RestController
@RequestMapping("/books")
public class BookController {@GetMappingpublic List<Book> getAllBooks() {return bookService.getAllBooks();}@GetMapping("/{id}")public Book getBookById(@PathVariable int id) {return bookService.getBookById(id);}@PostMappingpublic Book createBook(@RequestBody Book book) {return bookService.createBook(book);}@PutMapping("/{id}")public Book updateBook(@PathVariable int id, @RequestBody Book book) {return bookService.updateBook(id, book);}@DeleteMapping("/{id}")public void deleteBook(@PathVariable int id) {bookService.deleteBook(id);}
}
  • @RestController:标记控制器为 REST 风格。

  • @RequestMapping(“/books”):设置控制器的基础路径。
    k updateBook(@PathVariable int id, @RequestBody Book book) {
    return bookService.updateBook(id, book);
    }

    @DeleteMapping(“/{id}”)
    public void deleteBook(@PathVariable int id) {
    bookService.deleteBook(id);
    }
    }

- @RestController:标记控制器为 REST 风格。
- @RequestMapping("/books"):设置控制器的基础路径。
- @GetMapping、@PostMapping、@PutMapping、@DeleteMapping:简化了 HTTP 方法的注解。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词