当前位置: 代码网 > it编程>编程语言>Java > Spring Boot 数据验证与异常处理问题小结

Spring Boot 数据验证与异常处理问题小结

2026年03月30日 Java 我要评论
spring boot 数据验证与异常处理34.1 学习目标与重点提示学习目标:掌握spring boot数据验证与异常处理的核心概念与使用方法,包括数据验证的定义与特点、异常处理的定义与特点、spr

spring boot 数据验证与异常处理

34.1 学习目标与重点提示

学习目标:掌握spring boot数据验证与异常处理的核心概念与使用方法,包括数据验证的定义与特点、异常处理的定义与特点、spring boot与数据验证的集成、spring boot与异常处理的集成、spring boot的实际应用场景,学会在实际开发中处理数据验证与异常处理问题。
重点:数据验证的定义与特点异常处理的定义与特点spring boot与数据验证的集成spring boot与异常处理的集成spring boot的实际应用场景

34.2 数据验证与异常处理概述

数据验证与异常处理是java开发中的重要组件,用于确保数据的正确性和处理系统的异常。

34.2.1 数据验证的定义

定义:数据验证是指对输入数据进行验证,确保数据的正确性和完整性。
作用

  • 确保输入数据的正确性。
  • 防止恶意数据的输入。
  • 提高系统的可靠性。

常见的数据验证

  • 非空验证。
  • 长度验证。
  • 格式验证。
  • 范围验证。

✅ 结论:数据验证是指对输入数据进行验证,作用是确保输入数据的正确性、防止恶意数据的输入、提高系统的可靠性。

34.2.2 异常处理的定义

定义:异常处理是指对系统运行过程中出现的异常进行处理,确保系统的正常运行。
作用

  • 提高系统的可靠性。
  • 提高用户体验。
  • 便于系统的维护。

常见的异常处理

  • 异常捕获。
  • 异常转换。
  • 异常抛出。
  • 异常记录。

✅ 结论:异常处理是指对系统运行过程中出现的异常进行处理,作用是提高系统的可靠性、提高用户体验、便于系统的维护。

34.3 spring boot与数据验证的集成

spring boot与数据验证的集成是java开发中的重要内容。

34.3.1 集成spring validation的步骤

定义:集成spring validation的步骤是指使用spring boot与spring validation集成的方法。
步骤

  1. 创建spring boot项目。
  2. 添加所需的依赖。
  3. 配置数据验证。
  4. 创建实体类。
  5. 创建业务层。
  6. 创建控制器类。
  7. 测试应用。

示例
pom.xml文件中的依赖:

<dependencies>
    <!-- web依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- 数据验证依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-validation</artifactid>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的配置:

# 服务器端口
server.port=8080

实体类:

import javax.validation.constraints.*;
public class product {
    private long id;
    @notblank(message = "产品id不能为空")
    @size(min = 3, max = 10, message = "产品id长度必须在3到10个字符之间")
    private string productid;
    @notblank(message = "产品名称不能为空")
    @size(min = 2, max = 50, message = "产品名称长度必须在2到50个字符之间")
    private string productname;
    @min(value = 0, message = "价格必须大于等于0")
    @max(value = 10000, message = "价格必须小于等于10000")
    private double price;
    @min(value = 0, message = "库存必须大于等于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", "手机", 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", "耳机", 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", "产品添加成功");
        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", "产品更新成功");
        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", "产品删除成功");
        return result;
    }
}

应用启动类:

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);
    }
}

测试类:

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", "耳机");
        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();
    }
}

✅ 结论:集成spring validation的步骤包括创建spring boot项目、添加所需的依赖、配置数据验证、创建实体类、创建业务层、创建控制器类、测试应用。

34.4 spring boot与异常处理的集成

spring boot与异常处理的集成是java开发中的重要内容。

34.4.1 集成spring boot异常处理的步骤

定义:集成spring boot异常处理的步骤是指使用spring boot与异常处理集成的方法。
步骤

  1. 创建spring boot项目。
  2. 添加所需的依赖。
  3. 配置异常处理。
  4. 创建异常类。
  5. 创建异常处理器类。
  6. 测试应用。

示例
pom.xml文件中的依赖:

<dependencies>
    <!-- web依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- 数据验证依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-validation</artifactid>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的配置:

# 服务器端口
server.port=8080

实体类:

import javax.validation.constraints.*;
public class product {
    private long id;
    @notblank(message = "产品id不能为空")
    @size(min = 3, max = 10, message = "产品id长度必须在3到10个字符之间")
    private string productid;
    @notblank(message = "产品名称不能为空")
    @size(min = 2, max = 50, message = "产品名称长度必须在2到50个字符之间")
    private string productname;
    @min(value = 0, message = "价格必须大于等于0")
    @max(value = 10000, message = "价格必须小于等于10000")
    private double price;
    @min(value = 0, message = "库存必须大于等于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", "手机", 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", "耳机", 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", "系统错误:" + 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("产品不存在:" + 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", "产品添加成功");
        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", "产品更新成功");
        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", "产品删除成功");
        return result;
    }
}

应用启动类:

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);
    }
}

测试类:

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", "耳机");
        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();
    }
}

✅ 结论:集成spring boot异常处理的步骤包括创建spring boot项目、添加所需的依赖、配置异常处理、创建异常类、创建异常处理器类、测试应用。

34.5 spring boot的实际应用场景

在实际开发中,spring boot数据验证与异常处理的应用场景非常广泛,如:

  • 实现用户注册的数据验证。
  • 实现用户登录的数据验证。
  • 实现产品信息的数据验证。
  • 实现订单信息的数据验证。

示例

import javax.validation.constraints.*;
class product {
    private long id;
    @notblank(message = "产品id不能为空")
    @size(min = 3, max = 10, message = "产品id长度必须在3到10个字符之间")
    private string productid;
    @notblank(message = "产品名称不能为空")
    @size(min = 2, max = 50, message = "产品名称长度必须在2到50个字符之间")
    private string productname;
    @min(value = 0, message = "价格必须大于等于0")
    @max(value = 10000, message = "价格必须小于等于10000")
    private double price;
    @min(value = 0, message = "库存必须大于等于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", "手机", 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", "耳机", 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", "系统错误:" + 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("产品不存在:" + 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", "产品添加成功");
        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", "产品更新成功");
        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", "产品删除成功");
        return result;
    }
}
@springbootapplication
public class validationandexceptionapplication {
    public static void main(string[] args) {
        springapplication.run(validationandexceptionapplication.class, args);
    }
}
// 测试类
@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", "耳机");
        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();
    }
}

输出结果

  • 访问http://localhost:8080/api/products/add:返回“产品添加成功”。
  • 访问http://localhost:8080/api/products/10:返回“产品不存在”。

✅ 结论:在实际开发中,spring boot数据验证与异常处理的应用场景非常广泛,需要根据实际问题选择合适的数据验证和异常处理方法。

总结

本章我们学习了spring boot数据验证与异常处理,包括数据验证的定义与特点、异常处理的定义与特点、spring boot与数据验证的集成、spring boot与异常处理的集成、spring boot的实际应用场景,学会了在实际开发中处理数据验证与异常处理问题。其中,数据验证的定义与特点、异常处理的定义与特点、spring boot与数据验证的集成、spring boot与异常处理的集成、spring boot的实际应用场景是本章的重点内容。从下一章开始,我们将学习spring boot的其他组件、微服务等内容。

到此这篇关于spring boot 数据验证与异常处理问题小结的文章就介绍到这了,更多相关spring boot 数据验证与异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com