一个优秀的controller层逻辑
说到 controller,相信大家都不陌生,它可以很方便地对外提供数据接口。它的定位,我认为是「不可或缺的配角」,说它不可或缺是因为无论是传统的三层架构还是现在的cola架构,controller 层依旧有一席之地,说明他的必要性;说它是配角是因为 controller 层的代码一般是不负责具体的逻辑业务逻辑实现,但是它负责接收和响应请求
从现状看问题 controller 主要的工作有以下几项
接收请求并解析参数 调用 service 执行具体的业务代码(可能包含参数校验) 捕获业务逻辑异常做出反馈 业务逻辑执行成功做出响应 //dto@datapublic class testdto { private integer num; private string type;}//service@servicepublic class testservice { public double service(testdto testdto) throws exception { if (testdto.getnum() 1) { result = result * num; num -= 1; } return result; } throw new exception(未识别的算法); }}//controller@restcontrollerpublic class testcontroller { private testservice testservice; @postmapping(/test) public double test(@requestbody testdto testdto) { try { double result = this.testservice.service(testdto); return result; } catch (exception e) { throw new runtimeexception(e); } } @autowired public dtoid settestservice(testservice testservice) { this.testservice = testservice; }} 如果真的按照上面所列的工作项来开发 controller 代码会有几个问题
参数校验过多地耦合了业务代码,违背单一职责原则 可能在多个业务中都抛出同一个异常,导致代码重复 各种异常反馈和成功响应格式不统一,接口对接不友好 改造 controller 层逻辑 统一返回结构 统一返回值类型无论项目前后端是否分离都是非常必要的,方便对接接口的开发人员更加清晰地知道这个接口的调用是否成功(不能仅仅简单地看返回值是否为 null 就判断成功与否,因为有些接口的设计就是如此),使用一个状态码、状态信息就能清楚地了解接口调用情况
//定义返回数据结构public interface iresult { integer getcode(); string getmessage();}//常用结果的枚举public enum resultenum implements iresult { success(2001, 接口调用成功), validate_failed(2002, 参数校验失败), common_failed(2003, 接口调用失败), forbidden(2004, 没有权限访问资源); private integer code; private string message; //省略get、set方法和构造方法}//统一返回数据结构@data@noargsconstructor@allargsconstructorpublic class result { private integer code; private string message; private t data; public static result success(t data) { return new result(resultenum.success.getcode(), resultenum.success.getmessage(), data); } public static result success(string message, t data) { return new result(resultenum.success.getcode(), message, data); } public static result failed() { return new result(resultenum.common_failed.getcode(), resultenum.common_failed.getmessage(), null); } public static result failed(string message) { return new result(resultenum.common_failed.getcode(), message, null); } public static result failed(iresult errorresult) { return new result(errorresult.getcode(), errorresult.getmessage(), null); } public static result instance(integer code, string message, t data) { result result = new result(); result.setcode(code); result.setmessage(message); result.setdata(data); return result; }} 统一返回结构后,在 controller 中就可以使用了,但是每一个 controller 都写这么一段最终封装的逻辑,这些都是很重复的工作,所以还要继续想办法进一步处理统一返回结构
统一包装处理 spring 中提供了一个类 responsebodyadvice ,能帮助我们实现上述需求
responsebodyadvice 是对 controller 返回的内容在 httpmessageconverter 进行类型转换之前拦截,进行相应的处理操作后,再将结果返回给客户端。那这样就可以把统一包装的工作放到这个类里面。
public interface responsebodyadvice { boolean supports(methodparameter returntype, class convertertype); @nullable t beforebodywrite(@nullable t body, methodparameter returntype, mediatype selectedcontenttype, class selectedconvertertype, serverhttprequest request, serverhttpresponse response);} supports:判断是否要交给 beforebodywrite 方法执行,ture:需要;false:不需要 beforebodywrite:对 response 进行具体的处理 // 如果引入了swagger或knife4j的文档生成组件,这里需要仅扫描自己项目的包,否则文档无法正常生成@restcontrolleradvice(basepackages = com.example.demo)public class responseadvice implements responsebodyadvice { @override public boolean supports(methodparameter returntype, class convertertype) { // 如果不需要进行封装的,可以添加一些校验手段,比如添加标记排除的注解 return true; } @override public object beforebodywrite(object body, methodparameter returntype, mediatype selectedcontenttype, class selectedconvertertype, serverhttprequest request, serverhttpresponse response) { // 提供一定的灵活度,如果body已经被包装了,就不进行包装 if (body instanceof result) { return body; } return result.success(body); }} 经过这样改造,既能实现对 controller 返回的数据进行统一包装,又不需要对原有代码进行大量的改动
参数校验 java api 的规范 jsr303 定义了校验的标准 validation-api ,其中一个比较出名的实现是 hibernate validation ,spring validation 是对其的二次封装,常用于 springmvc 的参数自动校验,参数校验的代码就不需要再与业务逻辑代码进行耦合了
@pathvariable 和 @requestparam 参数校验 get 请求的参数接收一般依赖这两个注解,但是处于 url 有长度限制和代码的可维护性,超过 5 个参数尽量用实体来传参对 @pathvariable 和 @requestparam 参数进行校验需要在入参声明约束的注解
如果校验失败,会抛出 methodargumentnotvalidexception 异常
@restcontroller(value = prettytestcontroller)@requestmapping(/pretty)@validatedpublic class testcontroller { private testservice testservice; @getmapping(/{num}) public integer detail(@pathvariable(num) @min(1) @max(20) integer num) { return num * num; } @getmapping(/getbyemail) public testdto getbyaccount(@requestparam @notblank @email string email) { testdto testdto = new testdto(); testdto.setemail(email); return testdto; } @autowired public void settestservice(testservice prettytestservice) { this.testservice = prettytestservice; }} 校验原理 在 springmvc 中,有一个类是 requestresponsebodymethodprocessor ,这个类有两个作用(实际上可以从名字上得到一点启发)
用于解析 @requestbody 标注的参数 处理 @responsebody 标注方法的返回值 解析 @requestboyd 标注参数的方法是 resolveargument
public class requestresponsebodymethodprocessor extends abstractmessageconvertermethodprocessor { /** * throws methodargumentnotvalidexception if validation fails. * @throws httpmessagenotreadableexception if {@link requestbody#required()} * is {@code true} and there is no body content or if there is no suitable * converter to read the content with. */ @override public object resolveargument(methodparameter parameter, @nullable modelandviewcontainer mavcontainer, nativewebrequest webrequest, @nullable webdatabinderfactory binderfactory) throws exception { parameter = parameter.nestedifoptional(); //把请求数据封装成标注的dto对象 object arg = readwithmessageconverters(webrequest, parameter, parameter.getnestedgenericparametertype()); string name = conventions.getvariablenameforparameter(parameter); if (binderfactory != null) { webdatabinder binder = binderfactory.createbinder(webrequest, arg, name); if (arg != null) { //执行数据校验 validateifapplicable(binder, parameter); //如果校验不通过,就抛出methodargumentnotvalidexception异常 //如果我们不自己捕获,那么最终会由defaulthandlerexceptionresolver捕获处理 if (binder.getbindingresult().haserrors() && isbindexceptionrequired(binder, parameter)) { throw new methodargumentnotvalidexception(parameter, binder.getbindingresult()); } } if (mavcontainer != null) { mavcontainer.addattribute(bindingresult.model_key_prefix + name, binder.getbindingresult()); } } return adaptargumentifnecessary(arg, parameter); }}public abstract class abstractmessageconvertermethodargumentresolver implements handlermethodargumentresolver { /** * validate the binding target if applicable. * the default implementation checks for {@code @javax.validation.valid}, * spring's {@link org.springframework.validation.annotation.validated}, * and custom annotations whose name starts with valid. * @param binder the databinder to be used * @param parameter the method parameter descriptor * @since 4.1.5 * @see #isbindexceptionrequired */ protected void validateifapplicable(webdatabinder binder, methodparameter parameter) { //获取参数上的所有注解 annotation[] annotations = parameter.getparameterannotations(); for (annotation ann : annotations) { //如果注解中包含了@valid、@validated或者是名字以valid开头的注解就进行参数校验 object[] validationhints = validationannotationutils.determinevalidationhints(ann); if (validationhints != null) { //实际校验逻辑,最终会调用hibernate validator执行真正的校验 //所以spring validation是对hibernate validation的二次封装 binder.validate(validationhints); break; } } }} @requestbody 参数校验 post、put 请求的参数推荐使用 @requestbody 请求体参数
对 @requestbody 参数进行校验需要在 dto 对象中加入校验条件后,再搭配 @validated 即可完成自动校验如果校验失败,会抛出 constraintviolationexception 异常
//dto@datapublic class testdto { @notblank private string username; @notblank @length(min = 6, max = 20) private string password; @notnull @email private string email;}//controller@restcontroller(value = prettytestcontroller)@requestmapping(/pretty)public class testcontroller { private testservice testservice; @postmapping(/test-validation) public void testvalidation(@requestbody @validated testdto testdto) { this.testservice.save(testdto); } @autowired public void settestservice(testservice testservice) { this.testservice = testservice; }} 校验原理 声明约束的方式,注解加到了参数上面,可以比较容易猜测到是使用了 aop 对方法进行增强
而实际上 spring 也是通过 methodvalidationpostprocessor 动态注册 aop 切面,然后使用 methodvalidationinterceptor 对切点方法进行织入增强
public class methodvalidationpostprocessor extends abstractbeanfactoryawareadvisingpostprocessor implements initializingbean { //指定了创建切面的bean的注解 private class validatedannotationtype = validated.class; @override public void afterpropertiesset() { //为所有@validated标注的bean创建切面 pointcut pointcut = new annotationmatchingpointcut(this.validatedannotationtype, true); //创建advisor进行增强 this.advisor = new defaultpointcutadvisor(pointcut, createmethodvalidationadvice(this.validator)); } //创建advice,本质就是一个方法拦截器 protected advice createmethodvalidationadvice(@nullable validator validator) { return (validator != null ? new methodvalidationinterceptor(validator) : new methodvalidationinterceptor()); }}public class methodvalidationinterceptor implements methodinterceptor { @override public object invoke(methodinvocation invocation) throws throwable { //无需增强的方法,直接跳过 if (isfactorybeanmetadatamethod(invocation.getmethod())) { return invocation.proceed(); } class[] groups = determinevalidationgroups(invocation); executablevalidator execval = this.validator.forexecutables(); method methodtovalidate = invocation.getmethod(); set result; try { //方法入参校验,最终还是委托给hibernate validator来校验 //所以spring validation是对hibernate validation的二次封装 result = execval.validateparameters( invocation.getthis(), methodtovalidate, invocation.getarguments(), groups); } catch (illegalargumentexception ex) { ... } //校验不通过抛出constraintviolationexception异常 if (!result.isempty()) { throw new constraintviolationexception(result); } //controller方法调用 object returnvalue = invocation.proceed(); //下面是对返回值做校验,流程和上面大概一样 result = execval.validatereturnvalue(invocation.getthis(), methodtovalidate, returnvalue, groups); if (!result.isempty()) { throw new constraintviolationexception(result); } return returnvalue; }} 自定义校验规则 有些时候 jsr303 标准中提供的校验规则不满足复杂的业务需求,也可以自定义校验规则
自定义校验规则需要做两件事情
自定义注解类,定义错误信息和一些其他需要的内容 注解校验器,定义判定规则 //自定义注解类@target({elementtype.method, elementtype.field, elementtype.annotation_type, elementtype.constructor, elementtype.parameter})@retention(retentionpolicy.runtime)@documented@constraint(validatedby = mobilevalidator.class)public @interface mobile { /** * 是否允许为空 */ boolean required() default true; /** * 校验不通过返回的提示信息 */ string message() default 不是一个手机号码格式; /** * constraint要求的属性,用于分组校验和扩展,留空就好 */ class[] groups() default {}; class[] payload() default {};}//注解校验器public class mobilevalidator implements constraintvalidator { private boolean required = false; private final pattern pattern = pattern.compile(^1[34578][0-9]{9}$); // 验证手机号 /** * 在验证开始前调用注解里的方法,从而获取到一些注解里的参数 * * @param constraintannotation annotation instance for a given constraint declaration */ @override public void initialize(mobile constraintannotation) { this.required = constraintannotation.required(); } /** * 判断参数是否合法 * * @param value object to validate * @param context context in which the constraint is evaluated */ @override public boolean isvalid(charsequence value, constraintvalidatorcontext context) { if (this.required) { // 验证 return ismobile(value); } if (stringutils.hastext(value)) { // 验证 return ismobile(value); } return true; } private boolean ismobile(final charsequence str) { matcher m = pattern.matcher(str); return m.matches(); }} 自动校验参数真的是一项非常必要、非常有意义的工作。jsr303 提供了丰富的参数校验规则,再加上复杂业务的自定义校验规则,完全把参数校验和业务逻辑解耦开,代码更加简洁,符合单一职责原则。
更多关于 spring 参数校验请参考:
https://juejin.cn/post/6856541106626363399
自定义异常与统一拦截异常 原来的代码中可以看到有几个问题
抛出的异常不够具体,只是简单地把错误信息放到了 exception 中 抛出异常后,controller 不能具体地根据异常做出反馈 虽然做了参数自动校验,但是异常返回结构和正常返回结构不一致 自定义异常是为了后面统一拦截异常时,对业务中的异常有更加细颗粒度的区分,拦截时针对不同的异常作出不同的响应
而统一拦截异常的目的一个是为了可以与前面定义下来的统一包装返回结构能对应上,另一个是我们希望无论系统发生什么异常,http 的状态码都要是 200 ,尽可能由业务来区分系统的异常
//自定义异常public class forbiddenexception extends runtimeexception { public forbiddenexception(string message) { super(message); }}//自定义异常public class businessexception extends runtimeexception { public businessexception(string message) { super(message); }}//统一拦截异常@restcontrolleradvice(basepackages = com.example.demo)public class exceptionadvice { /** * 捕获 {@code businessexception} 异常 */ @exceptionhandler({businessexception.class}) public result handlebusinessexception(businessexception ex) { return result.failed(ex.getmessage()); } /** * 捕获 {@code forbiddenexception} 异常 */ @exceptionhandler({forbiddenexception.class}) public result handleforbiddenexception(forbiddenexception ex) { return result.failed(resultenum.forbidden); } /** * {@code @requestbody} 参数校验不通过时抛出的异常处理 */ @exceptionhandler({methodargumentnotvalidexception.class}) public result handlemethodargumentnotvalidexception(methodargumentnotvalidexception ex) { bindingresult bindingresult = ex.getbindingresult(); stringbuilder sb = new stringbuilder(校验失败:); for (fielderror fielderror : bindingresult.getfielderrors()) { sb.append(fielderror.getfield()).append(:).append(fielderror.getdefaultmessage()).append(, ); } string msg = sb.tostring(); if (stringutils.hastext(msg)) { return result.failed(resultenum.validate_failed.getcode(), msg); } return result.failed(resultenum.validate_failed); } /** * {@code @pathvariable} 和 {@code @requestparam} 参数校验不通过时抛出的异常处理 */ @exceptionhandler({constraintviolationexception.class}) public result handleconstraintviolationexception(constraintviolationexception ex) { if (stringutils.hastext(ex.getmessage())) { return result.failed(resultenum.validate_failed.getcode(), ex.getmessage()); } return result.failed(resultenum.validate_failed); } /** * 顶级异常捕获并统一处理,当其他异常无法处理时候选择使用 */ @exceptionhandler({exception.class}) public result handle(exception ex) { return result.failed(ex.getmessage()); }} 总结 做好了这一切改动后,可以发现 controller 的代码变得非常简洁,可以很清楚地知道每一个参数、每一个 dto 的校验规则,可以很明确地看到每一个 controller 方法返回的是什么数据,也可以方便每一个异常应该如何进行反馈
这一套操作下来后,我们能更加专注于业务逻辑的开发,代码简洁、功能完善,何乐而不为呢?
COMWIN仪器设备电源及供电注意事项及常见问题
AIoT生态系统走上云端 资源共享强化竞争力
iPhone8续航能力怎么样?续航测试大反转,让三星note8无地自容
DeepMind终于公开了它联合UCL的“高级深度强化学习课程”!
美日联手对抗台积电,欲攻克2nm工艺技术
一个优秀的Controller层逻辑
光纤的冷接和熔接,怎么选更合适?
湖泊检测智能型ORP传感器
自由电子和电子一样吗 自由电子怎么移动
VCSEL究竟带来了哪些“黑科技”呢?
广汽集团9月销售汽车24.36万辆,新能源汽车同比增长70.36%
谷歌发布针对Android2.2操作系统的软件开发工具包Fr
今年手机出货量或是十年来最低水平
吉林师范大学选购我司HS-100C高低温试验箱
MAX13054A CAN收发器的特性及使用介绍
分体型激光器的特点_分体型激光器的优势
嵌入式应用层开发学习曲线
通用自动驾驶都隐藏了哪些坑?
信号完整性之哪来的串扰?
新加坡交通物流企业访问团探访宏景智驾,共谋智能驾驶合作机会