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 方法的注解。