目录
当控制器处理了请求之后,向客户端响应的结果中,应该至少包含:
由于响应结果只有1个,但是需要同时包含业务状态和消息,应该使用JSON格式来组织这样的结果,例如:
{
"state": 1,
"message": "添加相册成功!"
}
或者:
{
"state": 2,
"message": "添加相册失败,尝试添加的相册名称已经被使用!"
}
在Spring MVC框架中,当需要响应JSON格式的字符串时,需要:
jackson-databind依赖项
spring-boot-starter-web中已经包含jackson-databind标签@EnableWebMvc注解则在项目的根包下创建web.JsonResult类,在类中声明JSON结果中对应的属性:
- package cn.tedu.csmall.product.web;
-
- import lombok.Data;
-
- @Data
- public class JsonResult {
-
- private Integer state;
- private String message;
-
- public static JsonResult ok() {
- JsonResult jsonResult = new JsonResult();
- jsonResult.state = ServiceCode.OK;
- return jsonResult;
- }
-
- }
然后,调整控制器中处理请求的方法的返回结果:
- @ApiOperation("添加相册")
- @PostMapping("/add-new")
- public JsonResult addNew(AlbumAddNewDTO albumAddNewDTO) {
- albumService.addNew(albumAddNewDTO);
- return JsonResult.ok();
- }
- if (response.data.state == 1) {
- // 成功
- } else if (response.data.state == 2) {
- // 失败:名称被占用
- alert(response.data.message);
- }
- login(){
- axios.post("/login",v.user).then(function (response) {
- if (response.data==1){
- location.href="/admin.html"; //跳转到后台管理页面
- }else if(response.data==2){
- v.\$message.error("用户名不存在!");
- }else{
- v.\$message.error("密码错误!");
- }
- })
- }
在JsonResult中设计了Integer state属性,用于表示“业务状态码”,由于此值是可以由客户端和服务器端协商的值,所以,值的大小不一定是固定的,例如“成功”,可以使用1表示,也可以使用200表示,只要协商一致即可,所以,在应用时,不应该直接将数值常量赋值到state属性上,否则,代码的可读性较差!
**反例:**jsonResult.state = 200;
应该将数值声明为常量来使用,以增加代码的可读性!
**正例:**jsonResult.state = ServiceCode.OK;
在设计方法时,如果使用Integer state作为参数,方法的调用者仍可能不使用声明的常量,而是直接传入某个未协商的直接常量值,例如,当设计了fail()方法时:
- public static JsonResult fail(Integer state, String message) {
- // ...
- }
则可能调用时传入错误的值:
JsonResult.fail(99999, e.getMessage());
由于state对应的值是相对有限的,是可以穷举的,则可以使用枚举来解决问题!
- package cn.tedu.csmall.product.web;
-
- public enum ServiceCode {
-
- OK(200),
- ERR_NOT_FOUND(404),
- ERR_CONFLICT(409);
-
- private Integer value;
-
- ServiceCode(Integer value) {
- this.value = value;
- }
-
- public Integer getValue() {
- return value;
- }
- }
如果将方法的参数设计为以上枚举类型,则方法的调用者只能传入以上列举的3个值中的某1个!例如将方法调整为:
- public static JsonResult fail(ServiceCode serviceCode, String message) {
- // ...
- }
调用时则是:
JsonResult.fail(ServiceCode.ERR_CONFLICT, e.getMessage());
个人主页:居然天上楼
感谢你这么可爱帅气还这么热爱学习~~
人生海海,山山而川
你的点赞👍 收藏⭐ 留言📝 加关注✅
是对我最大的支持与鞭策
