SpringBoot 接口对象 JSR校验及自定义异常捕获封装

本文介绍了一种在Spring Boot项目中实现JSR校验的方法,通过配置异常拦截机制来处理GET和POST请求中的数据验证。项目使用了Hibernate Validator进行字段验证,并自定义了错误响应格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jsr检验,接口对接中常用的校验方式,本文章只作记录,没有详述原理

项目结构:

  1. controller 里面有两个方法,一个是post方式的校验,一个是get方式的校验
  2. config 里面是定义的异常拦截机制,一个拦截post,一个拦截get
  3. vo 里面有两个实体,一个是返回结果的BaseOutput,一个测试用的校验实体

在这里插入图片描述
maven 依赖


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>boot</finalName>
	</build>

vo pack

public class BaseOutput<T> {
	
	private String code;
	
	private String message;
	
	private boolean flag;
	
	private T data;
	
	public static BaseOutput withSucc(Object data){
		BaseOutput out = new BaseOutput();
		out.setCode( "200");
		out.setFlag(true);
		out.setMessage("请求成功");
		out.setData(data);
		return out;
	}
	
	public static BaseOutput withFail(String message){
		BaseOutput out = new BaseOutput();
		out.setCode( "400");
		out.setFlag(false);
		out.setMessage(message);
		return out;
	}
	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}
	
	
}

import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;

public class ValidataEntivy {
	
	@NotNull(message = "name不能为空")
	private String name;
	@Email
	private String email;
	
	private String adress;
	@NotNull(message = "性别不能为空")
	private String sex;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAdress() {
		return adress;
	}

	public void setAdress(String adress) {
		this.adress = adress;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	

}

controller


import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import boot.vo.BaseOutput;
import boot.vo.ValidataEntivy;

@RestController
public class ValidataController {

	@RequestMapping("/validata")
	public void validata(@Validated ValidataEntivy validata){
		System.out.println(validata.getAdress());
	}
	
	@GetMapping("/test")
	public BaseOutput test( ValidataEntivy validata){
		return BaseOutput.withSucc(null);
	}
}

config 自定义异常捕获封装


import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import boot.vo.BaseOutput;

@RestControllerAdvice
public class ControllerArgumentExceptionHander {

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public BaseOutput methArgumentNotValidataException(MethodArgumentNotValidException e){
		BaseOutput out = BaseOutput.withSucc(null);
		StringBuffer message = new StringBuffer();
		BindingResult bindingResult = e.getBindingResult();
		if(bindingResult.hasErrors()){
			for (ObjectError objectError : bindingResult.getAllErrors()) {
				message.append(objectError.getDefaultMessage());
			}
			out = BaseOutput.withFail(message.toString());
		}
		return out ;
	}
	
	@ExceptionHandler(BindException.class)
	public BaseOutput BindException(BindException e){
		BaseOutput out = BaseOutput.withSucc(null);
		StringBuffer message = new StringBuffer();
		BindingResult bindingResult = e.getBindingResult();
		if(bindingResult.hasErrors()){
			for (ObjectError objectError : bindingResult.getAllErrors()) {
				message.append(objectError.getDefaultMessage()+"  ");
			}
			out = BaseOutput.withFail(message.toString());
		}
		return out ;
	}
}

ErrorPageRegistrarConfig 异常页面处理

package com.bitfty.cms.config;

import org.springframework.boot.web.server.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class ErrorPageRegistrarConfig implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage[] errorPages = new ErrorPage[2];
        // HttpStatus.NOT_FOUND跳转404页面
        errorPages[0] = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
        errorPages[1] = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/exception");
        registry.addErrorPages(errorPages);
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {

        //第二种写法:java8 lambda写法
        return (factory -> {
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
            factory.addErrorPages(errorPage404);
        });
    }
}

请求结果

  1. get 请求
    在这里插入图片描述
    post 请求
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值