Spring Boot 數(shù)據(jù)驗(yàn)證與異常處理問題小結(jié)
Spring Boot 數(shù)據(jù)驗(yàn)證與異常處理
34.1 學(xué)習(xí)目標(biāo)與重點(diǎn)提示
學(xué)習(xí)目標(biāo):掌握Spring Boot數(shù)據(jù)驗(yàn)證與異常處理的核心概念與使用方法,包括數(shù)據(jù)驗(yàn)證的定義與特點(diǎn)、異常處理的定義與特點(diǎn)、Spring Boot與數(shù)據(jù)驗(yàn)證的集成、Spring Boot與異常處理的集成、Spring Boot的實(shí)際應(yīng)用場(chǎng)景,學(xué)會(huì)在實(shí)際開發(fā)中處理數(shù)據(jù)驗(yàn)證與異常處理問題。
重點(diǎn):數(shù)據(jù)驗(yàn)證的定義與特點(diǎn)、異常處理的定義與特點(diǎn)、Spring Boot與數(shù)據(jù)驗(yàn)證的集成、Spring Boot與異常處理的集成、Spring Boot的實(shí)際應(yīng)用場(chǎng)景。
34.2 數(shù)據(jù)驗(yàn)證與異常處理概述
數(shù)據(jù)驗(yàn)證與異常處理是Java開發(fā)中的重要組件,用于確保數(shù)據(jù)的正確性和處理系統(tǒng)的異常。
34.2.1 數(shù)據(jù)驗(yàn)證的定義
定義:數(shù)據(jù)驗(yàn)證是指對(duì)輸入數(shù)據(jù)進(jìn)行驗(yàn)證,確保數(shù)據(jù)的正確性和完整性。
作用:
- 確保輸入數(shù)據(jù)的正確性。
- 防止惡意數(shù)據(jù)的輸入。
- 提高系統(tǒng)的可靠性。
常見的數(shù)據(jù)驗(yàn)證:
- 非空驗(yàn)證。
- 長(zhǎng)度驗(yàn)證。
- 格式驗(yàn)證。
- 范圍驗(yàn)證。
? 結(jié)論:數(shù)據(jù)驗(yàn)證是指對(duì)輸入數(shù)據(jù)進(jìn)行驗(yàn)證,作用是確保輸入數(shù)據(jù)的正確性、防止惡意數(shù)據(jù)的輸入、提高系統(tǒng)的可靠性。
34.2.2 異常處理的定義
定義:異常處理是指對(duì)系統(tǒng)運(yùn)行過程中出現(xiàn)的異常進(jìn)行處理,確保系統(tǒng)的正常運(yùn)行。
作用:
- 提高系統(tǒng)的可靠性。
- 提高用戶體驗(yàn)。
- 便于系統(tǒng)的維護(hù)。
常見的異常處理:
- 異常捕獲。
- 異常轉(zhuǎn)換。
- 異常拋出。
- 異常記錄。
? 結(jié)論:異常處理是指對(duì)系統(tǒng)運(yùn)行過程中出現(xiàn)的異常進(jìn)行處理,作用是提高系統(tǒng)的可靠性、提高用戶體驗(yàn)、便于系統(tǒng)的維護(hù)。
34.3 Spring Boot與數(shù)據(jù)驗(yàn)證的集成
Spring Boot與數(shù)據(jù)驗(yàn)證的集成是Java開發(fā)中的重要內(nèi)容。
34.3.1 集成Spring Validation的步驟
定義:集成Spring Validation的步驟是指使用Spring Boot與Spring Validation集成的方法。
步驟:
- 創(chuàng)建Spring Boot項(xiàng)目。
- 添加所需的依賴。
- 配置數(shù)據(jù)驗(yàn)證。
- 創(chuàng)建實(shí)體類。
- 創(chuàng)建業(yè)務(wù)層。
- 創(chuàng)建控制器類。
- 測(cè)試應(yīng)用。
示例:
pom.xml文件中的依賴:
<dependencies>
<!-- Web依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 數(shù)據(jù)驗(yàn)證依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- 測(cè)試依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的配置:
# 服務(wù)器端口 server.port=8080
實(shí)體類:
import javax.validation.constraints.*;
public class Product {
private Long id;
@NotBlank(message = "產(chǎn)品ID不能為空")
@Size(min = 3, max = 10, message = "產(chǎn)品ID長(zhǎng)度必須在3到10個(gè)字符之間")
private String productId;
@NotBlank(message = "產(chǎn)品名稱不能為空")
@Size(min = 2, max = 50, message = "產(chǎn)品名稱長(zhǎng)度必須在2到50個(gè)字符之間")
private String productName;
@Min(value = 0, message = "價(jià)格必須大于等于0")
@Max(value = 10000, message = "價(jià)格必須小于等于10000")
private double price;
@Min(value = 0, message = "庫(kù)存必須大于等于0")
private int stock;
public Product() {
}
public Product(Long id, String productId, String productName, double price, int stock) {
this.id = id;
this.productId = productId;
this.productName = productName;
this.price = price;
this.stock = stock;
}
// Getter和Setter方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", stock=" + stock +
'}';
}
}Repository接口:
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Repository
public class ProductRepository {
private List<Product> products = new ArrayList<>();
public ProductRepository() {
products.add(new Product(1L, "P001", "手機(jī)", 1000.0, 100));
products.add(new Product(2L, "P002", "電腦", 5000.0, 50));
products.add(new Product(3L, "P003", "電視", 3000.0, 80));
products.add(new Product(4L, "P004", "手表", 500.0, 200));
products.add(new Product(5L, "P005", "耳機(jī)", 300.0, 150));
}
public List<Product> getAllProducts() {
return products;
}
public Product getProductById(Long id) {
return products.stream().filter(product -> product.getId().equals(id)).findFirst().orElse(null);
}
public void addProduct(Product product) {
product.setId((long) (products.size() + 1));
products.add(product);
}
public void updateProduct(Product product) {
Product existingProduct = getProductById(product.getId());
if (existingProduct != null) {
existingProduct.setProductId(product.getProductId());
existingProduct.setProductName(product.getProductName());
existingProduct.setPrice(product.getPrice());
existingProduct.setStock(product.getStock());
}
}
public void deleteProduct(Long id) {
products.removeIf(product -> product.getId().equals(id));
}
}Service類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.getAllProducts();
}
public Product getProductById(Long id) {
return productRepository.getProductById(id);
}
public void addProduct(Product product) {
productRepository.addProduct(product);
}
public void updateProduct(Product product) {
productRepository.updateProduct(product);
}
public void deleteProduct(Long id) {
productRepository.deleteProduct(id);
}
}控制器類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
@PostMapping("/add")
public Map<String, Object> addProduct(@Valid @RequestBody Product product, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
result.put("success", false);
result.put("errors", errors);
return result;
}
productService.addProduct(product);
result.put("success", true);
result.put("message", "產(chǎn)品添加成功");
return result;
}
@PutMapping("/edit/{id}")
public Map<String, Object> editProduct(@PathVariable Long id, @Valid @RequestBody Product product, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
result.put("success", false);
result.put("errors", errors);
return result;
}
product.setId(id);
productService.updateProduct(product);
result.put("success", true);
result.put("message", "產(chǎn)品更新成功");
return result;
}
@DeleteMapping("/delete/{id}")
public Map<String, Object> deleteProduct(@PathVariable Long id) {
Map<String, Object> result = new HashMap<>();
productService.deleteProduct(id);
result.put("success", true);
result.put("message", "產(chǎn)品刪除成功");
return result;
}
}應(yīng)用啟動(dòng)類:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ValidationApplication {
public static void main(String[] args) {
SpringApplication.run(ValidationApplication.class, args);
}
}測(cè)試類:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.*;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ValidationApplicationTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void contextLoads() {
}
@Test
void testAddProduct() {
Map<String, Object> product = new HashMap<>();
product.put("productId", "P006");
product.put("productName", "耳機(jī)");
product.put("price", 300.0);
product.put("stock", 150);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(product, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"http://localhost:" + port + "/api/products/add",
HttpMethod.POST,
request,
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().get("success")).isEqualTo(true);
}
@Test
void testAddProductWithInvalidData() {
Map<String, Object> product = new HashMap<>();
product.put("productId", "P");
product.put("productName", "");
product.put("price", -100.0);
product.put("stock", -10);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(product, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"http://localhost:" + port + "/api/products/add",
HttpMethod.POST,
request,
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().get("success")).isEqualTo(false);
assertThat(response.getBody().get("errors")).isNotNull();
}
}? 結(jié)論:集成Spring Validation的步驟包括創(chuàng)建Spring Boot項(xiàng)目、添加所需的依賴、配置數(shù)據(jù)驗(yàn)證、創(chuàng)建實(shí)體類、創(chuàng)建業(yè)務(wù)層、創(chuàng)建控制器類、測(cè)試應(yīng)用。
34.4 Spring Boot與異常處理的集成
Spring Boot與異常處理的集成是Java開發(fā)中的重要內(nèi)容。
34.4.1 集成Spring Boot異常處理的步驟
定義:集成Spring Boot異常處理的步驟是指使用Spring Boot與異常處理集成的方法。
步驟:
- 創(chuàng)建Spring Boot項(xiàng)目。
- 添加所需的依賴。
- 配置異常處理。
- 創(chuàng)建異常類。
- 創(chuàng)建異常處理器類。
- 測(cè)試應(yīng)用。
示例:
pom.xml文件中的依賴:
<dependencies>
<!-- Web依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 數(shù)據(jù)驗(yàn)證依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- 測(cè)試依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的配置:
# 服務(wù)器端口 server.port=8080
實(shí)體類:
import javax.validation.constraints.*;
public class Product {
private Long id;
@NotBlank(message = "產(chǎn)品ID不能為空")
@Size(min = 3, max = 10, message = "產(chǎn)品ID長(zhǎng)度必須在3到10個(gè)字符之間")
private String productId;
@NotBlank(message = "產(chǎn)品名稱不能為空")
@Size(min = 2, max = 50, message = "產(chǎn)品名稱長(zhǎng)度必須在2到50個(gè)字符之間")
private String productName;
@Min(value = 0, message = "價(jià)格必須大于等于0")
@Max(value = 10000, message = "價(jià)格必須小于等于10000")
private double price;
@Min(value = 0, message = "庫(kù)存必須大于等于0")
private int stock;
public Product() {
}
public Product(Long id, String productId, String productName, double price, int stock) {
this.id = id;
this.productId = productId;
this.productName = productName;
this.price = price;
this.stock = stock;
}
// Getter和Setter方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", stock=" + stock +
'}';
}
}Repository接口:
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Repository
public class ProductRepository {
private List<Product> products = new ArrayList<>();
public ProductRepository() {
products.add(new Product(1L, "P001", "手機(jī)", 1000.0, 100));
products.add(new Product(2L, "P002", "電腦", 5000.0, 50));
products.add(new Product(3L, "P003", "電視", 3000.0, 80));
products.add(new Product(4L, "P004", "手表", 500.0, 200));
products.add(new Product(5L, "P005", "耳機(jī)", 300.0, 150));
}
public List<Product> getAllProducts() {
return products;
}
public Product getProductById(Long id) {
return products.stream().filter(product -> product.getId().equals(id)).findFirst().orElse(null);
}
public void addProduct(Product product) {
product.setId((long) (products.size() + 1));
products.add(product);
}
public void updateProduct(Product product) {
Product existingProduct = getProductById(product.getId());
if (existingProduct != null) {
existingProduct.setProductId(product.getProductId());
existingProduct.setProductName(product.getProductName());
existingProduct.setPrice(product.getPrice());
existingProduct.setStock(product.getStock());
}
}
public void deleteProduct(Long id) {
products.removeIf(product -> product.getId().equals(id));
}
}Service類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.getAllProducts();
}
public Product getProductById(Long id) {
return productRepository.getProductById(id);
}
public void addProduct(Product product) {
productRepository.addProduct(product);
}
public void updateProduct(Product product) {
productRepository.updateProduct(product);
}
public void deleteProduct(Long id) {
productRepository.deleteProduct(id);
}
}異常類:
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String message) {
super(message);
}
public ProductNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
public class ProductExistsException extends RuntimeException {
public ProductExistsException(String message) {
super(message);
}
public ProductExistsException(String message, Throwable cause) {
super(message, cause);
}
}異常處理器類:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class ProductExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, Object> result = new HashMap<>();
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
errors.put(error.getField(), error.getDefaultMessage());
});
result.put("success", false);
result.put("errors", errors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
}
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<Map<String, Object>> handleProductNotFoundException(ProductNotFoundException ex) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
}
@ExceptionHandler(ProductExistsException.class)
public ResponseEntity<Map<String, Object>> handleProductExistsException(ProductExistsException ex) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("message", "系統(tǒng)錯(cuò)誤:" + ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}控制器類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
Product product = productService.getProductById(id);
if (product == null) {
throw new ProductNotFoundException("產(chǎn)品不存在:" + id);
}
return product;
}
@PostMapping("/add")
public Map<String, Object> addProduct(@Valid @RequestBody Product product, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
result.put("success", false);
result.put("errors", errors);
return result;
}
productService.addProduct(product);
result.put("success", true);
result.put("message", "產(chǎn)品添加成功");
return result;
}
@PutMapping("/edit/{id}")
public Map<String, Object> editProduct(@PathVariable Long id, @Valid @RequestBody Product product, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
result.put("success", false);
result.put("errors", errors);
return result;
}
product.setId(id);
productService.updateProduct(product);
result.put("success", true);
result.put("message", "產(chǎn)品更新成功");
return result;
}
@DeleteMapping("/delete/{id}")
public Map<String, Object> deleteProduct(@PathVariable Long id) {
Map<String, Object> result = new HashMap<>();
productService.deleteProduct(id);
result.put("success", true);
result.put("message", "產(chǎn)品刪除成功");
return result;
}
}應(yīng)用啟動(dòng)類:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ValidationAndExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(ValidationAndExceptionApplication.class, args);
}
}測(cè)試類:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.*;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ValidationAndExceptionApplicationTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void contextLoads() {
}
@Test
void testAddProduct() {
Map<String, Object> product = new HashMap<>();
product.put("productId", "P006");
product.put("productName", "耳機(jī)");
product.put("price", 300.0);
product.put("stock", 150);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(product, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"http://localhost:" + port + "/api/products/add",
HttpMethod.POST,
request,
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().get("success")).isEqualTo(true);
}
@Test
void testAddProductWithInvalidData() {
Map<String, Object> product = new HashMap<>();
product.put("productId", "P");
product.put("productName", "");
product.put("price", -100.0);
product.put("stock", -10);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(product, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"http://localhost:" + port + "/api/products/add",
HttpMethod.POST,
request,
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(response.getBody().get("success")).isEqualTo(false);
assertThat(response.getBody().get("errors")).isNotNull();
}
@Test
void testGetProductById() {
ResponseEntity<Product> response = restTemplate.getForEntity("http://localhost:" + port + "/api/products/1", Product.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
}
@Test
void testGetProductByIdNotFound() {
ResponseEntity<Map> response = restTemplate.getForEntity("http://localhost:" + port + "/api/products/10", Map.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getBody().get("success")).isEqualTo(false);
assertThat(response.getBody().get("message")).isNotNull();
}
}? 結(jié)論:集成Spring Boot異常處理的步驟包括創(chuàng)建Spring Boot項(xiàng)目、添加所需的依賴、配置異常處理、創(chuàng)建異常類、創(chuàng)建異常處理器類、測(cè)試應(yīng)用。
34.5 Spring Boot的實(shí)際應(yīng)用場(chǎng)景
在實(shí)際開發(fā)中,Spring Boot數(shù)據(jù)驗(yàn)證與異常處理的應(yīng)用場(chǎng)景非常廣泛,如:
- 實(shí)現(xiàn)用戶注冊(cè)的數(shù)據(jù)驗(yàn)證。
- 實(shí)現(xiàn)用戶登錄的數(shù)據(jù)驗(yàn)證。
- 實(shí)現(xiàn)產(chǎn)品信息的數(shù)據(jù)驗(yàn)證。
- 實(shí)現(xiàn)訂單信息的數(shù)據(jù)驗(yàn)證。
示例:
import javax.validation.constraints.*;
class Product {
private Long id;
@NotBlank(message = "產(chǎn)品ID不能為空")
@Size(min = 3, max = 10, message = "產(chǎn)品ID長(zhǎng)度必須在3到10個(gè)字符之間")
private String productId;
@NotBlank(message = "產(chǎn)品名稱不能為空")
@Size(min = 2, max = 50, message = "產(chǎn)品名稱長(zhǎng)度必須在2到50個(gè)字符之間")
private String productName;
@Min(value = 0, message = "價(jià)格必須大于等于0")
@Max(value = 10000, message = "價(jià)格必須小于等于10000")
private double price;
@Min(value = 0, message = "庫(kù)存必須大于等于0")
private int stock;
public Product() {
}
public Product(Long id, String productId, String productName, double price, int stock) {
this.id = id;
this.productId = productId;
this.productName = productName;
this.price = price;
this.stock = stock;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", stock=" + stock +
'}';
}
}
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Repository
class ProductRepository {
private List<Product> products = new ArrayList<>();
public ProductRepository() {
products.add(new Product(1L, "P001", "手機(jī)", 1000.0, 100));
products.add(new Product(2L, "P002", "電腦", 5000.0, 50));
products.add(new Product(3L, "P003", "電視", 3000.0, 80));
products.add(new Product(4L, "P004", "手表", 500.0, 200));
products.add(new Product(5L, "P005", "耳機(jī)", 300.0, 150));
}
public List<Product> getAllProducts() {
return products;
}
public Product getProductById(Long id) {
return products.stream().filter(product -> product.getId().equals(id)).findFirst().orElse(null);
}
public void addProduct(Product product) {
product.setId((long) (products.size() + 1));
products.add(product);
}
public void updateProduct(Product product) {
Product existingProduct = getProductById(product.getId());
if (existingProduct != null) {
existingProduct.setProductId(product.getProductId());
existingProduct.setProductName(product.getProductName());
existingProduct.setPrice(product.getPrice());
existingProduct.setStock(product.getStock());
}
}
public void deleteProduct(Long id) {
products.removeIf(product -> product.getId().equals(id));
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.getAllProducts();
}
public Product getProductById(Long id) {
return productRepository.getProductById(id);
}
public void addProduct(Product product) {
productRepository.addProduct(product);
}
public void updateProduct(Product product) {
productRepository.updateProduct(product);
}
public void deleteProduct(Long id) {
productRepository.deleteProduct(id);
}
}
class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String message) {
super(message);
}
public ProductNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
class ProductExistsException extends RuntimeException {
public ProductExistsException(String message) {
super(message);
}
public ProductExistsException(String message, Throwable cause) {
super(message, cause);
}
}
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
class ProductExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, Object> result = new HashMap<>();
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
errors.put(error.getField(), error.getDefaultMessage());
});
result.put("success", false);
result.put("errors", errors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
}
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<Map<String, Object>> handleProductNotFoundException(ProductNotFoundException ex) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
}
@ExceptionHandler(ProductExistsException.class)
public ResponseEntity<Map<String, Object>> handleProductExistsException(ProductExistsException ex) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("message", "系統(tǒng)錯(cuò)誤:" + ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/products")
class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
Product product = productService.getProductById(id);
if (product == null) {
throw new ProductNotFoundException("產(chǎn)品不存在:" + id);
}
return product;
}
@PostMapping("/add")
public Map<String, Object> addProduct(@Valid @RequestBody Product product, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
result.put("success", false);
result.put("errors", errors);
return result;
}
productService.addProduct(product);
result.put("success", true);
result.put("message", "產(chǎn)品添加成功");
return result;
}
@PutMapping("/edit/{id}")
public Map<String, Object> editProduct(@PathVariable Long id, @Valid @RequestBody Product product, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
Map<String, String> errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
result.put("success", false);
result.put("errors", errors);
return result;
}
product.setId(id);
productService.updateProduct(product);
result.put("success", true);
result.put("message", "產(chǎn)品更新成功");
return result;
}
@DeleteMapping("/delete/{id}")
public Map<String, Object> deleteProduct(@PathVariable Long id) {
Map<String, Object> result = new HashMap<>();
productService.deleteProduct(id);
result.put("success", true);
result.put("message", "產(chǎn)品刪除成功");
return result;
}
}
@SpringBootApplication
public class ValidationAndExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(ValidationAndExceptionApplication.class, args);
}
}
// 測(cè)試類
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ValidationAndExceptionApplicationTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void contextLoads() {
}
@Test
void testAddProduct() {
Map<String, Object> product = new HashMap<>();
product.put("productId", "P006");
product.put("productName", "耳機(jī)");
product.put("price", 300.0);
product.put("stock", 150);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(product, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"http://localhost:" + port + "/api/products/add",
HttpMethod.POST,
request,
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().get("success")).isEqualTo(true);
}
@Test
void testAddProductWithInvalidData() {
Map<String, Object> product = new HashMap<>();
product.put("productId", "P");
product.put("productName", "");
product.put("price", -100.0);
product.put("stock", -10);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(product, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"http://localhost:" + port + "/api/products/add",
HttpMethod.POST,
request,
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(response.getBody().get("success")).isEqualTo(false);
assertThat(response.getBody().get("errors")).isNotNull();
}
@Test
void testGetProductById() {
ResponseEntity<Product> response = restTemplate.getForEntity("http://localhost:" + port + "/api/products/1", Product.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
}
@Test
void testGetProductByIdNotFound() {
ResponseEntity<Map> response = restTemplate.getForEntity("http://localhost:" + port + "/api/products/10", Map.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getBody().get("success")).isEqualTo(false);
assertThat(response.getBody().get("message")).isNotNull();
}
}輸出結(jié)果:
- 訪問http://localhost:8080/api/products/add:返回“產(chǎn)品添加成功”。
- 訪問http://localhost:8080/api/products/10:返回“產(chǎn)品不存在”。
? 結(jié)論:在實(shí)際開發(fā)中,Spring Boot數(shù)據(jù)驗(yàn)證與異常處理的應(yīng)用場(chǎng)景非常廣泛,需要根據(jù)實(shí)際問題選擇合適的數(shù)據(jù)驗(yàn)證和異常處理方法。
總結(jié)
本章我們學(xué)習(xí)了Spring Boot數(shù)據(jù)驗(yàn)證與異常處理,包括數(shù)據(jù)驗(yàn)證的定義與特點(diǎn)、異常處理的定義與特點(diǎn)、Spring Boot與數(shù)據(jù)驗(yàn)證的集成、Spring Boot與異常處理的集成、Spring Boot的實(shí)際應(yīng)用場(chǎng)景,學(xué)會(huì)了在實(shí)際開發(fā)中處理數(shù)據(jù)驗(yàn)證與異常處理問題。其中,數(shù)據(jù)驗(yàn)證的定義與特點(diǎn)、異常處理的定義與特點(diǎn)、Spring Boot與數(shù)據(jù)驗(yàn)證的集成、Spring Boot與異常處理的集成、Spring Boot的實(shí)際應(yīng)用場(chǎng)景是本章的重點(diǎn)內(nèi)容。從下一章開始,我們將學(xué)習(xí)Spring Boot的其他組件、微服務(wù)等內(nèi)容。
到此這篇關(guān)于Spring Boot 數(shù)據(jù)驗(yàn)證與異常處理問題小結(jié)的文章就介紹到這了,更多相關(guān)Spring Boot 數(shù)據(jù)驗(yàn)證與異常處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot+Hibernate實(shí)現(xiàn)自定義數(shù)據(jù)驗(yàn)證及異常處理
- 從拋出異常到返回JSON/XML:SpringBoot?異常處理全鏈路深度解析
- Spring Boot 全局異常處理策略設(shè)計(jì)之@ExceptionHandler 與 @ControllerAdvice 生效原理源碼解析
- springboot全局異常處理方式
- Spring?Boot全局異常處理實(shí)戰(zhàn)指南
- SpringBoot異常處理機(jī)制使用詳解
- Spring Boot 中的默認(rèn)異常處理機(jī)制解析(如 /error 接口)
- SpringBoot中的統(tǒng)一異常處理詳細(xì)解析
- SpringBoot全局異常處理機(jī)制和配置攔截器方式
相關(guān)文章
Java保留兩位小數(shù)的實(shí)現(xiàn)方法
這篇文章主要介紹了 Java保留兩位小數(shù)的實(shí)現(xiàn)方法的相關(guān)資料,需要的朋友可以參考下2017-06-06
Java多線程和并發(fā)基礎(chǔ)面試題(問答形式)
多線程和并發(fā)問題是Java技術(shù)面試中面試官比較喜歡問的問題之一。在這里,從面試的角度列出了大部分重要的問題,感興趣的小伙伴們可以參考一下2016-06-06
Spring?Boot?集成并開發(fā)?Sa-token示例詳解
Sa-token是一款高可用的權(quán)限認(rèn)證框架,他帶我們用最簡(jiǎn)化的配置完成用?spring?security?需要進(jìn)行大量配置的才能完成的工作,這篇文章主要介紹了Spring?Boot?集成并開發(fā)?Sa-token,需要的朋友可以參考下2023-06-06
Springcloud hystrix服務(wù)熔斷和dashboard如何實(shí)現(xiàn)
這篇文章主要介紹了Springcloud hystrix服務(wù)熔斷和dashboard如何實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12
Java和c語言隨機(jī)數(shù)Random代碼詳細(xì)
這篇文章主要介紹Java和c語言得隨機(jī)數(shù)Random,隨機(jī)數(shù)的用處在生活中比較少見,但是用處并不少,比如一些小游戲的制作等等。下面我們就一起來學(xué)習(xí)這篇關(guān)于Java和c隨機(jī)數(shù)Random得文章吧2021-10-10
JAVA 根據(jù)Url把多文件打包成ZIP下載實(shí)例
這篇文章主要介紹了JAVA 根據(jù)Url把多文件打包成ZIP下載的相關(guān)資料,需要的朋友可以參考下2017-08-08
使用Java讀取Excel文件數(shù)據(jù)的方法詳解
通過編程方式讀取Excel數(shù)據(jù)能實(shí)現(xiàn)數(shù)據(jù)導(dǎo)入、批量處理、數(shù)據(jù)比對(duì)和更新等任務(wù)的自動(dòng)化,本文為大家介紹了三種Java讀取Excel文件數(shù)據(jù)的方法,需要的可以參考下2024-01-01

