Code ví dụ Spring Boot RESTful Webservice (CRUD)
(Xem lại: Web Service là gì?)
(Xem lại: Giới thiệu về RESTful web service.)
(Xem lại: Code ví dụ, tạo RESTful Web Service với Spring MVC)
Các công nghệ sử dụng:
- Spring Boot 2.0.1
- Maven
- JDK 1.8
- Eclipse + Spring Tool Suite
Tạo Spring Boot Project:
Cấu trúc Project
Khi tạo project Spring Boot nó sẽ tự động thêm các thư viện jackson để mapping dữ liệu trả về sang dạng JSON
File entities:
package stackjava.com.sbrestful.entities;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(value = { "password" })
public class User {
private int id;
private String username;
private String password;
public User() {
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
// getter - setter
}
Khi trả về đối tượng User mình sẽ bỏ qua trường password (thông tin nhạy cảm) và các trường bị null.
File Controller:
package stackjava.com.sbrestful.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class BaseController {
@RequestMapping("/")
public String index() {
return "index";
}
}
package stackjava.com.sbrestful.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import stackjava.com.sbrestful.entities.User;
@RestController
@RequestMapping("/rest")
public class UserRestController {
public static HashMap<Integer, User> mapUser = new HashMap<Integer, User>();
static {
mapUser.put(1, new User(1, "kai", "123456"));
mapUser.put(2, new User(2, "admin", "admin1234"));
mapUser.put(3, new User(3, "sena", "123456"));
mapUser.put(4, new User(4, "peter", "1234"));
}
/* ---------------- GET ALL USER ------------------------ */
@RequestMapping(value = "/users", method = RequestMethod.GET)
public ResponseEntity<List<User>> getAllUser() {
List<User> listUser = new ArrayList<User>(mapUser.values());
return new ResponseEntity<List<User>>(listUser, HttpStatus.OK);
}
/* ---------------- GET USER BY ID ------------------------ */
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> getUserById(@PathVariable int id) {
User user = mapUser.get(id);
if (user != null) {
return new ResponseEntity<Object>(user, HttpStatus.OK);
}
return new ResponseEntity<Object>("Not Found User", HttpStatus.NO_CONTENT);
}
/* ---------------- CREATE NEW USER ------------------------ */
@RequestMapping(value = "/users", method = RequestMethod.POST)
public ResponseEntity<String> createUser(@RequestBody User user) {
if (mapUser.containsKey(user.getId())) {
return new ResponseEntity<String>("User Already Exist!", HttpStatus.CONFLICT);
}
mapUser.put(user.getId(), user);
return new ResponseEntity<String>("Created!", HttpStatus.CREATED);
}
/* ---------------- DELETE USER ------------------------ */
@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteUserById(@PathVariable int id) {
User user = mapUser.get(id);
if (user == null) {
return new ResponseEntity<String>("Not Found User", HttpStatus.OK);
}
mapUser.remove(id);
return new ResponseEntity<String>("Deleted!", HttpStatus.OK);
}
/* ---------------- UPDATE USER ------------------------ */
@RequestMapping(value = "/users", method = RequestMethod.PUT)
public ResponseEntity<String> updateUser(@RequestBody User user) {
User oldUser = mapUser.get(user.getId());
if (oldUser == null) {
return new ResponseEntity<String>("Not Found User", HttpStatus.NO_CONTENT);
}
// replace old user by new user.
mapUser.put(user.getId(), user);
return new ResponseEntity<String>("Updated!", HttpStatus.OK);
}
}
File view:
<html> <head> </head> <body> <h1>Demo Spring Boot RESTful Web Service</h1> <br /> <a href="/rest/users">/users</a> <br /> <a href="/rest/users/1">/users/1</a> <br /> </body> </html>
Demo:
Ở đây mình dùng postman extension trên chrome để gửi các request thêm, sửa, xóa, update đối tượng user.
Lấy tất cả các đối tượng user:
Tạo mới đối tượng user (id = 7, username = “nobody”, password = “xxx”)
Lấy danh sách tất cả user 1 lần nữa ta sẽ thấy có thêm đối tượng user với id = 7.
Tương tự các bạn có thể thực hiện các request xóa, update đối tượng user như trên.
(Xem thêm: Code ví dụ Spring Boot RESTful Webservice với MySQL)
(Xem thêm: Code ví dụ Spring Boot RESTful Webservice với MongoDB)
Code ví dụ Spring Boot RESTful Webservice (CRUD) stackjava.com
Okay, Done!
Download code ví dụ trên tại đây.
References:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/