如何写好controller层
前言
本篇主要要介绍的就是controller层的处理,一个完整的后端请求由4部分组成:
1. 接口地址(也就是URL地址)、
2. 请求方式(一般就是get、set,当然还有put、delete)、
3. 请求数据(request,有head跟body)、
4. 响应数据(response)
本篇将解决以下3个问题:
当接收到请求时,如何优雅的校验参数
返回响应数据该如何统一的进行处理
接收到请求,处理业务逻辑时抛出了异常又该如何处理
一、Controller层参数接收
常见的请求就分为get跟post2种
@RestController
@RequestMapping("/product/product-info")
public class ProductInfoController {@AutowiredProductInfoService productInfoService;@GetMapping("/findById")public ProductInfoQueryVo findById(Integer id) {...}@PostMapping("/page")public IPage findPage(Page page, ProductInfoQueryVo vo) {...}
}
@RestController: 之前解释过,@RestController = @Controller + ResponseBody。加上这个注解,springboot就会吧这个类当成controller进行处理,然后把所有返回的参数放到ResponseBody中
@RequestMapping: 请求的前缀,也就是所有该Controller下的请求都需要加上/product/product-info的前缀
@GetMapping("/findById"): 标志这是一个get请求,并且需要通过/findById地址才可以访问到
@PostMapping("/page"): 同理,表示是个post请求
参数: 至于参数部分,只需要写上ProductInfoQueryVo,前端过来的json请求便会通过映射赋值到对应的对象中,例如请求这么写,productId就会自动被映射到vo对应的属性当中
size : 1
current : 1
productId : 1
productName : 泡脚
二、统一状态码
1. 返回格式
为了跟前端妹妹打好关系,我们通常需要对后端返回的数据进行包装一下,增加一下状态码,状态信息,这样前端妹妹接收到数据就可以根据不同的状态码,判断响应数据状态,是否成功是否异常进行不同的显示。当然这让你拥有了更多跟前端妹妹的交流机会,假设我们约定了1000就是成功的意思
如果你不封装,那么返回的数据是这样子的
{"productId": 1,"productName": "泡脚","productPrice": 100.00,"productDescription": "中药泡脚加按摩","productStatus": 0,
}
经过封装以后时这样子的
{"code": 1000,"msg": "请求成功","data": {"productId": 1,"productName": "泡脚","productPrice": 100.00,"productDescription": "中药泡脚加按摩","productStatus": 0,}
}
2. 封装ResultVo
这些状态码肯定都是要预先编好的,怎么编呢?写个常量1000?还是直接写死1000?要这么写就真的书白读的了,写状态码当然是用枚举拉
首先先定义一个状态码的接口,所有状态码都需要实现它,有了标准才好做事
public interface StatusCode {public int getCode();public String getMsg();
}
然后去找前端妹妹,跟他约定好状态码(这可能是你们唯一的约定了)枚举类嘛,当然不能有setter方法了,因此我们不能在用@Data注解了,我们要用@Getter
@Getter
public enum ResultCode implements StatusCode{SUCCESS(1000, "请求成功"),FAILED(1001, "请求失败"),VALIDATE_ERROR(1002, "参数校验失败"),RESPONSE_PACK_ERROR(1003, "response返回包装失败");private int code;private String msg;ResultCode(int code, String msg) {this.code = code;this.msg = msg;}
}
写好枚举类开始写ResultVo包装类了,我们预设了几种默认的方法,比如成功的话就默认传入object就可以了,我们自动包装成success
@Data
public class ResultVo {// 状态码private int code;// 状态信息private String msg;// 返回对象private Object data;// 手动设置返回vopublic ResultVo(int code, String msg, Object data) {this.code = code;this.msg = msg;this.data = data;}// 默认返回成功状态码,数据对象public ResultVo(Object data) {this.code = ResultCode.SUCCESS.getCode();this.msg = ResultCode.SUCCESS.getMsg();this.data = data;}// 返回指定状态码,数据对象public ResultVo(StatusCode statusCode, Object data) {this.code = statusCode.getCode();this.msg = statusCode.getMsg();this.data = data;}// 只返回状态码public ResultVo(StatusCode statusCode) {this.code = statusCode.getCode();this.msg = statusCode.getMsg();this.data = null;}
}
使用,现在的返回肯定就不是return data;这么简单了,而是需要new ResultVo(data);
@PostMapping("/findByVo")
public ResultVo findByVo(@Validated ProductInfoVo vo) {ProductInfo productInfo = new ProductInfo();BeanUtils.copyProperties(vo, productInfo);return new ResultVo(productInfoService.getOne(new QueryWrapper(productInfo)));
}
最后返回就会是上面带了状态码的数据了
三、统一校验
1. 原始做法
假设有一个添加ProductInfo的接口,在没有统一校验时,我们需要这么做
@Data
public class ProductInfoVo {// 商品名称private String productName;// 商品价格private BigDecimal productPrice;// 上架状态private Integer productStatus;
}
@PostMapping("/findByVo")
public ProductInfo findByVo(ProductInfoVo vo) {if (StringUtils.isNotBlank(vo.getProductName())) {throw new APIException("商品名称不能为空");}if (null != vo.getProductPrice() && vo.getProductPrice().compareTo(new BigDecimal(0)) < 0) {throw new APIException("商品价格不能为负数");}...ProductInfo productInfo = new ProductInfo();BeanUtils.copyProperties(vo, productInfo);return new ResultVo(productInfoService.getOne(new QueryWrapper(productInfo)));
}
这if写的人都傻了,能忍吗?肯定不能忍啊
2. @Validated参数校验
好在有@Validated,又是一个校验参数必备良药了。有了@Validated我们只需要再vo上面加一点小小的注解,便可以完成校验功能
@Data
public class ProductInfoVo {@NotNull(message = "商品名称不允许为空")private String productName;@Min(value = 0, message = "商品价格不允许为负数")private BigDecimal productPrice;private Integer productStatus;
}
@PostMapping("/findByVo")
public ProductInfo findByVo(@Validated ProductInfoVo vo) {ProductInfo productInfo = new ProductInfo();BeanUtils.copyProperties(vo, productInfo);return new ResultVo(productInfoService.getOne(new QueryWrapper(productInfo)));
}
运行看看,如果参数不对会发生什么?
我们故意传一个价格为-1的参数过去
productName : 泡脚
productPrice : -1
productStatus : 1
{"timestamp": "2020-04-19T03:06:37.268+0000","status": 400,"error": "Bad Request","errors": [{"codes": ["Min.productInfoVo.productPrice","Min.productPrice","Min.java.math.BigDecimal","Min"],"arguments": [{"codes": ["productInfoVo.productPrice","productPrice"],"defaultMessage": "productPrice","code": "productPrice"},0],"defaultMessage": "商品价格不允许为负数","objectName": "productInfoVo","field": "productPrice","rejectedValue": -1,"bindingFailure": false,"code": "Min"}],"message": "Validation failed for object\u003d\u0027productInfoVo\u0027. Error count: 1","trace": "org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object \u0027productInfoVo\u0027 on field \u0027productPrice\u0027: rejected value [-1]; codes [Min.productInfoVo.productPrice,Min.productPrice,Min.java.math.BigDecimal,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productInfoVo.productPrice,productPrice]; arguments []; default message [productPrice],0]; default message [商品价格不允许为负数]\n\tat org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:164)\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:124)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.base/java.lang.Thread.run(Thread.java:830)\n","path": "/leilema/product/product-info/findByVo"
}
大功告成了吗?虽然成功校验了参数,也返回了异常,并且带上"商品价格不允许为负数"的信息。但是你要是这样返回给前端,前端妹妹就提刀过来了,当年约定好的状态码,你个负心人说忘就忘?用户体验小于等于0啊!所以我们要进行优化一下,每次出现异常的时候,自动把状态码写好,不负妹妹之约!
拓展:关于参数的验证:
具体参考 Springboot整合JSR303参数校验
3. 优化异常处理
首先我们先看看校验参数抛出了什么异常
Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
我们看到代码抛出了org.springframework.validation.BindException的绑定异常,因此我们的思路就是AOP拦截所有controller,然后异常的时候统一拦截起来,进行封装!完美!
玩你个头啊完美,这么呆瓜的操作springboot不知道吗?spring mvc当然知道拉,所以给我们提供了一个@RestControllerAdvice来增强所有@RestController,然后使用@ExceptionHandler注解,就可以拦截到对应的异常。
这里我们就拦截BindException.class就好了。最后在返回之前,我们对异常信息进行包装一下,包装成ResultVo,当然要跟上ResultCode.VALIDATE_ERROR的异常状态码。这样前端妹妹看到VALIDATE_ERROR的状态码,就会调用数据校验异常的弹窗提示用户哪里没填好
@RestControllerAdvice
public class ControllerExceptionAdvice {@ExceptionHandler({BindException.class})public ResultVo MethodArgumentNotValidExceptionHandler(BindException e) {// 从异常对象中拿到ObjectError对象ObjectError objectError = e.getBindingResult().getAllErrors().get(0);return new ResultVo(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());}
}
来康康效果,完美。1002与前端妹妹约定好的状态码
{"code": 1002,"msg": "参数校验失败","data": "商品价格不允许为负数"
}
这里可以以上的枚举可以规定好不同的业务模块对应的编号,大型系统一般有指定生成的;不同的业务异常分不同的枚举类来规定不同的业务异常信息;规范很重要,尤其是对外的api,良好的规范利于系统后期维护和迭代,有利于bug的定位和查找。
当然这是全局异常的处理方式:从全局的角度来
在局部上,指定捕获业务异常的方式,也用户提示;
以下为业务异常的类BusinessException 通过抛业对应的业务异常来给用户提示。将错误信息置于message中。
package com.bzcst.bop.common.exception;public class BusinessException extends RuntimeException {private int code;private String msg;public BusinessException(String msg) {super(msg);this.code = 1;this.msg = msg;}public BusinessException(int code, String msg) {super(msg);this.code = code;this.msg = msg;}public BusinessException(String msg, Throwable cause) {super(msg, cause);this.code = 1;this.msg = msg;}public BusinessException(int code, String msg, Throwable cause) {super(msg, cause);this.code = code;this.msg = msg;}public BusinessException(ErrorEnum errorEnum) {super(errorEnum.message);this.code = errorEnum.errorCode;this.msg = errorEnum.message;}public BusinessException(ErrorEnum errorEnum, Throwable cause) {super(errorEnum.message, cause);this.code = errorEnum.errorCode;this.msg = errorEnum.message;}public int getCode() {return this.code;}public String getMsg() {return this.msg;}public void setCode(final int code) {this.code = code;}public void setMsg(final String msg) {this.msg = msg;}public boolean equals(final Object o) {if (o == this) {return true;} else if (!(o instanceof BusinessException)) {return false;} else {BusinessException other = (BusinessException)o;if (!other.canEqual(this)) {return false;} else if (this.getCode() != other.getCode()) {return false;} else {Object this$msg = this.getMsg();Object other$msg = other.getMsg();if (this$msg == null) {if (other$msg != null) {return false;}} else if (!this$msg.equals(other$msg)) {return false;}return true;}}}protected boolean canEqual(final Object other) {return other instanceof BusinessException;}public int hashCode() {int PRIME = true;int result = 1;int result = result * 59 + this.getCode();Object $msg = this.getMsg();result = result * 59 + ($msg == null ? 43 : $msg.hashCode());return result;}public String toString() {return "BusinessException(code=" + this.getCode() + ", msg=" + this.getMsg() + ")";}
}
四、统一响应
1. 统一包装响应
再回头看一下controller层的返回
return new ResultVo(productInfoService.getOne(new QueryWrapper(productInfo)));
开发小哥肯定不乐意了,谁有空天天写new ResultVo(data)啊,我就想返回一个实体!怎么实现我不管!好把,那就是AOP拦截所有Controller,再@After的时候统一帮你封装一下咯
怕是上一次脸打的不够疼,springboot能不知道这么个操作吗?
@RestControllerAdvice(basePackages = {"com.bugpool.leilema"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {@Overridepublic boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {// response是ResultVo类型,或者注释了NotControllerResponseAdvice都不进行包装return !methodParameter.getParameterType().isAssignableFrom(ResultVo.class);}@Overridepublic Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {// String类型不能直接包装if (returnType.getGenericParameterType().equals(String.class)) {ObjectMapper objectMapper = new ObjectMapper();try {// 将数据包装在ResultVo里后转换为json串进行返回return objectMapper.writeValueAsString(new ResultVo(data));} catch (JsonProcessingException e) {throw new APIException(ResultCode.RESPONSE_PACK_ERROR, e.getMessage());}}// 否则直接包装成ResultVo返回return new ResultVo(data);}
}
@RestControllerAdvice(basePackages = {"com.bugpool.leilema"})自动扫描了所有指定包下的controller,在Response时进行统一处理
重写supports方法,也就是说,当返回类型已经是ResultVo了,那就不需要封装了,当不等与ResultVo时才进行调用beforeBodyWrite方法,跟过滤器的效果是一样的
最后重写我们的封装方法beforeBodyWrite,注意除了String的返回值有点特殊,无法直接封装成json,我们需要进行特殊处理,其他的直接new ResultVo(data);就ok了
打完收工,康康效果
@PostMapping("/findByVo")
public ProductInfo findByVo(@Validated ProductInfoVo vo) {ProductInfo productInfo = new ProductInfo();BeanUtils.copyProperties(vo, productInfo);return productInfoService.getOne(new QueryWrapper(productInfo));
}
此时就算我们返回的是po,接收到的返回就是标准格式了,开发小哥露出了欣慰的笑容
{"code": 1000,"msg": "请求成功","data": {"productId": 1,"productName": "泡脚","productPrice": 100.00,"productDescription": "中药泡脚加按摩","productStatus": 0,...}
}
目前很多公司的项目一般都是要去包装,给人感觉很机械,应该去灵活处理
2. NOT统一响应
不开启统一响应原因
开发小哥是开心了,可是其他系统就不开心了。举个例子:我们项目中集成了一个健康检测的功能,也就是这货
@RestController
public class HealthController {@GetMapping("/health")public String health() {return "success";}
}
没办法,人家是老大,人家要的返回不是
{"code": 1000,"msg": "请求成功","data": "success"
}
人家要的返回只要一个success,人家定的标准不可能因为你一个系统改。俗话说的好,如果你改变不了环境,那你就只能我****
新增不进行封装注解
因为百分之99的请求还是需要包装的,只有个别不需要,写在包装的过滤器吧?又不是很好维护,那就加个注解好了。所有不需要包装的就加上这个注解。
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotControllerResponseAdvice {
}
然后在我们的增强过滤方法上过滤包含这个注解的方法
@RestControllerAdvice(basePackages = {"com.bugpool.leilema"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {@Overridepublic boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {// response是ResultVo类型,或者注释了NotControllerResponseAdvice都不进行包装return !(methodParameter.getParameterType().isAssignableFrom(ResultVo.class)|| methodParameter.hasMethodAnnotation(NotControllerResponseAdvice.class));}...
最后就在不需要包装的方法上加上注解
@RestController
public class HealthController {@GetMapping("/health")@NotControllerResponseAdvicepublic String health() {return "success";}
}
这时候就不会自动封装了,而其他没加注解的则依旧自动包装

它通过切面编程+注释的方式来同一处理一些个别需求,是一个处理问题的逻辑!
五、统一异常
每个系统都会有自己的业务异常,比如库存不能小于0子类的,这种异常并非程序异常,而是业务操作引发的异常,我们也需要进行规范的编排业务异常状态码,并且写一个专门处理的异常类,最后通过刚刚学习过的异常拦截统一进行处理,以及打日志
1.异常状态码枚举,既然是状态码,那就肯定要实现我们的标准接口StatusCode
@Getter
public enum AppCode implements StatusCode {APP_ERROR(2000, "业务异常"),PRICE_ERROR(2001, "价格异常");private int code;private String msg;AppCode(int code, String msg) {this.code = code;this.msg = msg;}
}
2.异常类,这里需要强调一下,code代表AppCode的异常状态码,也就是2000;msg代表业务异常,这只是一个大类,一般前端会放到弹窗title上;最后super(message);这才是抛出的详细信息,在前端显示在弹窗体中,在ResultVo则保存在data中
@Getter
public class APIException extends RuntimeException {private int code;private String msg;// 手动设置异常public APIException(StatusCode statusCode, String message) {// message用于用户设置抛出错误详情,例如:当前价格-5,小于0super(message);// 状态码this.code = statusCode.getCode();// 状态码配套的msgthis.msg = statusCode.getMsg();}// 默认异常使用APP_ERROR状态码public APIException(String message) {super(message);this.code = AppCode.APP_ERROR.getCode();this.msg = AppCode.APP_ERROR.getMsg();}}
3.最后进行统一异常的拦截,这样无论在service层还是controller层,开发人员只管抛出API异常,不需要关系怎么返回给前端,更不需要关心日志的打印
@RestControllerAdvice
public class ControllerExceptionAdvice {@ExceptionHandler({BindException.class})public ResultVo MethodArgumentNotValidExceptionHandler(BindException e) {// 从异常对象中拿到ObjectError对象ObjectError objectError = e.getBindingResult().getAllErrors().get(0);return new ResultVo(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());}@ExceptionHandler(APIException.class)public ResultVo APIExceptionHandler(APIException e) {// log.error(e.getMessage(), e); 由于还没集成日志框架,暂且放着,写上TODOreturn new ResultVo(e.getCode(), e.getMsg(), e.getMessage());}
}
4.最后使用,我们的代码只需要这么写
if (null == orderMaster) {throw new APIException(AppCode.ORDER_NOT_EXIST, "订单号不存在:" + orderId);
}
{"code": 2003,"msg": "订单不存在","data": "订单号不存在:1998"
}
就会自动抛出AppCode.ORDER_NOT_EXIST状态码的响应,并且带上异常详细信息订单号不存在:xxxx。后端小哥开发有效率,前端妹妹获取到2003状态码,调用对应警告弹窗,title写上订单不存在,body详细信息记载"订单号不存在:1998"。同时日志还自动打上去了!当然为了避免data 的二意性,可以只让前端展示msg即可;data可以在排查问题时查看。
ps:一般对于controller 的处理一般公司都会封装成脚手架,拿来直接用即可,但是构建原理都大同小异!
相关文章:

如何写好controller层
前言本篇主要要介绍的就是controller层的处理,一个完整的后端请求由4部分组成:1. 接口地址(也就是URL地址)、2. 请求方式(一般就是get、set,当然还有put、delete)、3. 请求数据(request,有head跟body)、4. 响应数据(response)本篇…...

MySQL---视图的概念与操作
MySQL—视图的概念与操作 常见的数据库对象 对象描述表(TABLE)表是存储数据的逻辑单元,以行和列的形式存在,列就是字段,行就是记录数据字典就是系统表,存放数据库相关信息的表。系统表的数据通常由数据库系统维护, 程…...

ChatGPT,会是现实世界的MOSS吗?
最近,两个人工智能系统彻底火出了圈,成为许多网友热议的焦点。 一个是冷酷无情的“幕后主角”MOSS,一个是多才多艺的“全能网友”ChatGPT。 先来说说MOSS。今年春节档,科幻电影《流浪地球2》热映,电影中一个面试环节令…...

安卓大厂面试题_安卓开发面经_Android大厂面经(22/30)之JNI全解析
系列专栏: 《150道安卓常见面试题全解析》 安卓专栏目录见帖子 : 安卓面经_anroid面经_150道安卓常见基础面试题全解析 安卓系统Framework面经专栏:《Android系统Framework面试题解析大全》 安卓系统Framework面经目录详情:Android系统面经_Framework开发面经_150道面试题答…...

记一次docker虚拟机横向移动渗透测试
本次渗透在几个docker虚拟机间多次横向移动,最终找到了一个可以进行docker逃逸的出口,拿下服务器。渗透过程曲折但充满了乐趣,入口是172.17.0.6的docker虚拟机,然后一路横向移动,最终在172.17.0.2出实现了docker逃逸&a…...

计算机网络-物理层
计算机网络-物理层 计算机网络学习笔记 学习视频:https://www.bilibili.com/video/BV1c4411d7jb/?p14&spm_id_from333.1007.top_right_bar_window_history.content.click&vd_source75dce036dc8244310435eaf03de4e330 物理层的基本概念 物理层考虑的是怎样…...

Kubernetes Nginx 发布
kubernetes发布nginx 目录 Nginx Pod启动Service访问Nginx 2.1. NodePort访问Nginx 2.2. ClusterIP访问Nginx 2.3. LoadBalancer访问Nginx 2.4. ExternalName访问NginxDeployment方式部署Nginx 3.1 Nginx Replicas Nginx Pod 启动 nginx-v1.yaml apiVersion: v1 kind: Pod…...

华为OD机试真题Python实现【非严格递增连续数字序列】真题+解题思路+代码(20222023)
非严格递增连续数字序列 题目 输入一个字符串仅包含大小写字母和数字 求字符串中包含的最长的非严格递增连续数字序列长度 比如: 12234 属于非严格递增数字序列 🔥🔥🔥🔥🔥👉👉👉👉👉👉 华为OD机试(Python)真题目录汇总 ## 输入 输入一个字符串仅…...

12-render函数
render函数 一、render的作用 非单文件组件时,创建vm的写法: new Vue({el: #root,template: <App></App>,components: {App} })但是该写法在脚手架中会报错。因为脚手架默认引入的是个残缺版的vue。 如果要避免报错,有2种解决…...

磨金石教育摄影技能干货分享|杨元惺佳作欣赏——诗意人文
一般来说,人文摄影总会体现现实性多些。但杨老师是个摄影诗人,他的内心总能将刻板的现实融入美好的光芒。你在他的照片里,看着现实的摄影素材,所感受到的是诗意的绵绵未尽。春网(中国)正所谓春水碧于天&…...

在Pandas中通过时间频率来汇总数据的三种常用方法
当我们的数据涉及日期和时间时,分析随时间变化变得非常重要。Pandas提供了一种方便的方法,可以按不同的基于时间的间隔(如分钟、小时、天、周、月、季度或年)对时间序列数据进行分组。 在Pandas中,有几种基于日期对数据进行分组的方法。我们将…...

基于SPI的增强式插件框架设计
很久之前,为了诊断线上的问题,就想要是能有工具可以在线上出问题的时候,放个诊断包进去马上生效,就能看到线上问题的所在,那该是多么舒服的事情。后来慢慢的切换到 java 领域后,这种理想也变成了现实&#…...

176、【动态规划】leetcode ——1143. 最长公共子序列(C++版本)
题目描述 原题链接:1143. 最长公共子序列 题目描述 本题和 718. 最长重复子数组(动态规划) 的区别在于此时不要求令一个数组中元素连续。 动态规划五步曲: (1)dp[i][j]含义: 截止到text1[i …...

16行代码采集原神官网角色全图+全语音
嗨害大家好鸭!我是小熊猫~ 本来是不玩原神的, 但是实在是经不住诱惑鸭~ 毕竟谁能拒绝可以爬树、炸鱼、壶里造房子、抓小动物、躲猫猫的对战游戏捏~ 准备工具 源码资料电子书:点击此处跳转文末名片获取 准备模块 import requests import re import ex…...

Unity(二)--通过简单例子了解UGUI几个常用对象操作(Text,Image,Button)
目录 文本框等UI对象的添加Canvas 画布给Canvas添加脚本,绑定要操作的对象文本框Text的使用图像Image的使用更换图片Type:显示图片相关按钮Button的使用过渡导航事件绑定文本框等UI对象的添加 Canvas 画布 所有的UI元素的父物体,。 当创建一个UI元素的时候,如果没有Canvas…...

手写一个文件上传demo
背景 最近闲来无事,同事闻了一下上传文件的基本操作,如何用文件流来实现一个文件的上传功能 基本概念 流(Stream)是指在计算机的输入输出操作中各部件之间的数据流动。可以按照数据传输的方向,将流可分为输入流和输出…...

通过 Apifox Echo 了解 Content-Length
Content-Length 用以指定 Body 的体积。响应头中的 Content-Length 指定 Response Body 的体积,请求头中的 Content-Length 指定 Request Body 的体积。 通过 Content-Length,HTTP 客户端/服务器端将会根据该头部计算出 Body 的大小。 请求头中的 Cont…...

ESP32设备驱动-CPU频率设置
CPU频率设置 文章目录 CPU频率设置1、ESP32的CPU频率介绍1.1 CPU时钟1.2 外设时钟2、CPU频率设置API3、软件准备4、硬件准备5、CPU频率设置实例5.1 CPU频率读取5.2 CPU频率设置在本文中,将介绍如何通过Arduino Core设置或更改ESP32 CPU时钟速度(频率)。 1、ESP32的CPU频率介…...

超声波风速风向传感器的技术参数
技术参数 风速 ◆ 启动风速:0.1m/s ◆ 测量范围:0~30m/s(可定制) ◆ 测量精度:(0.2m/s0.02*v)(v为真实风速) ◆ 分 辨 率:0.01m/s 风向 ◆ 测量范围:0~359 ◆ 测量精度&a…...

【vue2每日小知识】实现store中modules模块的封装与自动导入
🥳博 主:初映CY的前说(前端领域) 🌞个人信条:想要变成得到,中间还有做到! 🤘本文核心:省去我们store仓库中分模块时的需要每次导入index的问题 目录 【前言】在store中如何简…...

【Leetcode 剑指Offer】第3天 字符串(简单)
字符串剑指 Offer 05. 替换空格字符串构造函数和析构函数操作函数剑指 Offer 58 - II. 左旋转字符串剑指 Offer 05. 替换空格 题:实现一个函数,把字符串 s 中的每个空格替换成"%20"。 class Solution { public:string replaceSpace(string s…...

【双指针问题】LeetCode344、345、 844、283问题详解及代码实现
Halo,这里是Ppeua。平时主要更新C语言,C,数据结构算法......感兴趣就关注我吧!你定不会失望。 🌈个人主页:主页链接 🌈算法专栏:专栏链接 我会一直往里填充内容哒! &…...

Linux基础命令-netstat显示网络状态
文章目录 netstat 命令介绍 语法格式 基本参数 显示各列内容分析 1)netstat -a显示各列内容分析 2)netstat -r显示各列内容分析 3)netstat -i 显示各列内容分析 参考实例 1)显示系统网络状态的所有连接 2)…...

液氮恒温器(电学)T9015的技术规格
液氮型低温恒温器,利用液氮作为降温媒介,标准恒温器可实现快速降温至液氮温度(约20min),其工作原理是在恒温器内部液氮腔内装入液氮,通过调整控温塞与冷指的间隙来保持冷指的漏热稳定在一定值上,…...

字节跳动大规模实践埋点自动化测试框架设计
大数据时代,多数的web或app产品都会使用第三方或自己开发相应的数据系统,进行用户行为数据或其它信息数据的收集,在这个过程中,埋点是比较重要的一环。 埋点收集的数据一般有以下作用: 驱动决策:ABtest、漏…...

自动化测试优势和劣势
一、自动化测试概述 软件自动化测试是相对手工测试而存在的,由测试人员根据测试用例中描述的规程一步步执行测试,得到实际结果与期望结果的比较。在此过程中,节省人力、时间或硬件资源,提高测试效率。 二、自动化测试优势&劣…...

数据结构---顺序表
专栏:数据结构 个人主页:HaiFan. 专栏简介:从零开始,数据结构!! 顺序表前言接口实现SListInit初始化和SListDestory销毁SListPrint打印表中的元素SListCheckCapacity检查表中空间SListPushBack尾插和SListP…...

springboot基础
文章目录[toc]SpringBoot概述spring springmvc springboot的关系Spring Boot简介微服务springboot的优点核心功能SpringBoot搭建使用IDEA快速搭建 Spring Boot项目入门案例研究项目结构pom 文件主程序类,主入口类配置文件、加载顺序开启配置文件注释配置文件和加载顺…...

华为OD机试真题Python实现【 时间格式化】真题+解题思路+代码(20222023)
时间格式化 题目 运维工程师采集到某产品线网运行一天产生的日志n条 现需根据日志时间先后顺序对日志进行排序 日志时间格式为H:M:S.N H表示小时(0~23) M表示分钟(0~59) S表示秒(0~59) N表示毫秒(0~999) 时间可能并没有补全 也就是说 01:01:01.001也可能表示为1:1:1.1 🔥�…...

android kotlin 协程(五) suspend与continuation
android kotlin 协程(五) suspend与continuation 通过本篇你将学会: suspendCoroutine{} suspendCancellableCoroutine{} suspend 与 continuation suspendCoroutine 第一次看到这玩意的时候肯定有点身体不适, 先不用管这个东西是什么, 目前为止 只需要知道 suspendCoro…...