使用注解对controller接口入参进行常用的校验(springboot + hibernate-validator)

源码地址:https://gitee.com/yk001/base.git

将hibernate-validator用于Controller,可以有效的规范api输入
并且在接口联调阶段,将不规范的请求挡在外部,规范调用方的入参。

1,引入包

		<dependency>
			<groupId>org.hibernate.validator</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>6.1.6.Final</version>
		</dependency>

2,controller

package com.yukang.base.controller;


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

import javax.validation.constraints.Max;


/**
 * Function: Hibernate-Validator使用demo. <br/>
 * Date:     2020/12/13 3:29 下午<br/>
 *
 * @author yukang
 */
@RestController
@Validated
public class ValidatorController {

    @GetMapping("/entity")
    public String getEntity(
            @Max(10) @RequestParam(name="p1") Integer p1,
            @Max(10) @RequestParam(name="p2") Integer p2,
            @Max(10) @RequestParam(name="p3")  Integer p3) {
        return "success";
    }

}

3,添加统一的异常处理

package com.yukang.base.config;

import com.yukang.base.common.CommonResultCode;
import com.yukang.base.common.GeneralResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;


/**
 * Function: GlobalExcept. <br/>
 * Date:     11/13/18 5:20 PM<br/>
 *
 * @see
 * @since JDK 1.8
 */
@Slf4j
@ControllerAdvice("com.yukang.base.controller")
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public GeneralResult otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        GeneralResult tempResult = new GeneralResult();
        tempResult.setCode(CommonResultCode.OPERATION_FAILED_UNKOWN);
        tempResult.setDescription(ex.getMessage());
        return tempResult;
    }

}

4,验证

curl -X GET "http://localhost:9001/entity?p1=15&p2=15&p3=15" -H "accept: */*"
{
  "code": 101,
  "data": null,
  "description": "getEntity.p1: 最大不能超过10, getEntity.p2: 最大不能超过10, getEntity.p3: 最大不能超过10"
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值