美文网首页
秒杀第五节:定义通用的返回对象-返回正确信息

秒杀第五节:定义通用的返回对象-返回正确信息

作者: 小石读史 | 来源:发表于2020-07-16 09:42 被阅读0次

新建package名字response。新建类CommonReturnType

@Data
public class CommonReturnType {
    //表明对应请求的返回处理结果“success”或“fail"
    private String status;

    //若status=success,则data内返回前端需要的json数据
    //若status=fail,则data内使用通用的错误码格式
    private Object data;

    //定义一个通用的创建方法
    public static CommonReturnType create(Object result) {
        return CommonReturnType.create(result,"success");

    }
    public static CommonReturnType create(Object result, String status) {
        CommonReturnType type = new CommonReturnType();
        type.setStatus(status);
        type.setData(result);
        return type;
    }
   
}

优化UserController查询接口

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/get")
    public CommonReturnType getUser(@RequestParam(name = "id") Integer id){
        //调用service服务获取对应id对象返回给前端
        UserModel userModel = userService.getUserById(id);
        //将核心领域模型用户对象转换为可供UI使用的viewobject
        UserVo userVo = convertFromMode(userModel);
        return CommonReturnType.create(userVo);
    }

    private UserVo convertFromMode(UserModel userModel) {
        if (userModel == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userModel, userVo);
        return userVo;
    }
}

请求地址:http://localhost:8080/user/get?id=6
返回值:{"status":"success","data":{"id":6,"name":"test","gender":1,"age":22,"telphone":"12312312311"}}

相关文章

网友评论

      本文标题:秒杀第五节:定义通用的返回对象-返回正确信息

      本文链接:https://www.haomeiwen.com/subject/gugqcktx.html