详解Java后端优雅验证参数合法性
程序员文章站
2023-01-13 16:43:30
1、首先创建一个测试实体类person,并携带如上注解,其注解的作用描述在messagepackage com.clickpaas.pojo;import com.fasterxml.jackson....
1、首先创建一个测试实体类person,并携带如上注解,其注解的作用描述在message
package com.clickpaas.pojo; import com.fasterxml.jackson.annotation.jsonformat; import lombok.data; import org.hibernate.validator.constraints.length; import org.hibernate.validator.constraints.range; import javax.validation.constraints.*; import java.math.bigdecimal; import java.util.date; import java.util.list; /** * @author 方延杰 * @version 1.0 * @since 2020/12/10 9:04 下午 */ @data public class person { @null(message = "death必须为null") private string death; @asserttrue(message = "bool必须为true") private boolean bool; @assertfalse(message = "fal必须为false") private boolean fal; @min(value = 1, message = "min必须为数字,其值大于或等于指定的最小值") private integer min; @max(value = 10, message = "max必须为数字,其值小于或等于指定的最大值") private integer max; @decimalmin(value = "1", message = "mindeci最小不能小于1") private bigdecimal mindeci; @decimalmax(value = "10", message = "maxdeci最大不能大于10") private bigdecimal maxdeci; @size(min = 1, max = 2, message = "list集合的长度最小不能小于1,最大不能大于2") private list<object> list; @digits(integer = 4, fraction = 2, message = "digits整数位不能超过4个,小数位不能超过2个") private bigdecimal digits; /** * 将前台传来的日期数据映射到此字段 */ @jsonformat(shape = jsonformat.shape.string, pattern = "yyyy-mm-dd hh:mm:ss", timezone = "gmt+8") @past(message = "past必须为过去的日期") private date past; @jsonformat(shape = jsonformat.shape.string, pattern = "yyyy-mm-dd hh:mm:ss", timezone = "gmt+8") @future(message = "future必须为将来的日期") private date future; @pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "phone必须符合正则表达式") private string phone; @email(message = "email必须是邮箱格式") private string email; @length(min = 1, max = 2, message = "length长度最小不能小于1,最大不能大于2") private string length; @notempty(message = "id不能为null,长度大于0") private string id; @range(min = 1, max = 12, message = "month最小不能小于1,最大不能大于12") private integer month; @notblank(message = "name不能为null,字段串长度大于0(限字符串)") private string name; }
2、封装返回响应体
package com.clickpaas.response; import lombok.allargsconstructor; import lombok.data; /** * @author 方延杰 * @version 1.0 * @since 2019/7/3 4:32 下午 */ @data @allargsconstructor public class codemsg { private int code; private string msg; /** * 失败 */ public static codemsg server_error = new codemsg(500, "服务端异常"); }
package com.clickpaas.response; import lombok.allargsconstructor; import lombok.data; /** * @author 方延杰 * @version 1.0 * @since 2019/7/3 4:35 下午 */ @data @allargsconstructor public class result<t> { /** * 返回状态码 除200其余全部失败 */ private int code; /** * 返回信息 除success其余全部失败 */ private string msg; /** * 泛型数据 */ private t data; /** * 成功时返回的类型 * * @param data 数据 * @param <t> 泛型 * @return 泛型数据 */ public static <t> result<t> success(t data) { return new result<>(200, "success", data); } public static <t> result<t> fail(codemsg codemsg) { return new result<>(codemsg); } private result(codemsg codemsg) { if (codemsg == null) { return; } this.code = codemsg.getcode(); this.msg = codemsg.getmsg(); } }
3、创建使用增强器拦截并返回异常信息
package com.clickpaas.config; import com.clickpaas.response.codemsg; import com.clickpaas.response.result; import org.springframework.web.bind.methodargumentnotvalidexception; import org.springframework.web.bind.annotation.exceptionhandler; import org.springframework.web.bind.annotation.restcontrolleradvice; import javax.servlet.http.httpservletrequest; import java.util.objects; /** * @author 方延杰 * @version 1.0 * @since 2018/12/10 4:59 下午 */ @restcontrolleradvice public class globalexceptioninterceptor { @exceptionhandler(value = methodargumentnotvalidexception.class) public result<object> exceptionhandler(httpservletrequest request, exception e) { string errmsg = "处理失败"; if (e instanceof methodargumentnotvalidexception) { // 拿到参数校验具体异常信息 errmsg = objects.requirenonnull(((methodargumentnotvalidexception) e).getbindingresult().getfielderror()).getdefaultmessage(); } return result.fail(new codemsg(500, errmsg)); } }
4、创建控制层测试
package com.clickpaas.controller; import com.clickpaas.pojo.person; import org.springframework.validation.annotation.validated; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.restcontroller; /** * @author 方延杰 * @version 1.0 * @since 2020/12/10 9:03 下午 */ @restcontroller public class validcontroller { @postmapping("/valid") public string valid(@validated @requestbody person person) { return "success"; } }
5、测试符合验证请求体访问,请求体如下:
{ "death":null, "bool":true, "fal":false, "min":1, "max":10, "mindeci":1, "maxdeci":10, "list":[ {},{} ], "digits":1144.12, "past":"2020-10-01 10:00:00", "future":"2022-10-01 10:00:00", "phone":"15900445584", "email":"yanjie.fang@clickpaas.com", "length":"ab", "id":" ", "name":"a" }
6、故意修改不符合验证的数据
7、如果想做整体验证,如下:
package com.clickpaas.uitl; import javax.validation.constraintviolation; import javax.validation.validation; import javax.validation.validator; import java.util.list; import java.util.set; import java.util.stream.collectors; /** * bean整体校验工具类 * * @author 方延杰 * @version 1.0 * @since 2020/12/10 10:08 下午 */ public class validatorutils { private static final validator validator = validation.builddefaultvalidatorfactory().getvalidator(); /** * bean整体校验,有不合规范,拼接message */ public static string validate(object obj, class<?>... groups) { stringbuilder errormessage = new stringbuilder(); set<constraintviolation<object>> resultset = validator.validate(obj, groups); if (resultset.size() > 0) { //如果存在错误结果,则将其解析并进行拼凑后异常抛出 list<string> errormessagelist = resultset.stream().map(constraintviolation::getmessage).collect(collectors.tolist()); errormessagelist.foreach(o -> errormessage.append(o).append(";")); } return errormessage.tostring(); } }
8、整体测试类
到此这篇关于详解java后端优雅验证参数合法性的文章就介绍到这了,更多相关java 验证参数合法性内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 微软正在利用Minecraft来训练AI