从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统03创建RESTful API,并统一处理返回值
Posted Java全栈从0到1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统03创建RESTful API,并统一处理返回值相关的知识,希望对你有一定的参考价值。
本节应用Spring对RESTful的支持,使用了如@RestController等注解实现RESTful控制器。
如果对Spring中的RESTful不太明白,请查看相关书籍
1、创建一个数据对象,用来统一RESTful API的返回格式
package com.ltsolution.framework.common.msgmodel; import java.util.HashMap; import java.util.Map; public class AppResult { private String status; private String error; private String message; private Map<String, Object> data = new HashMap<String, Object>(); public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } public AppResult ok(String statusMsg) { this.status="200"; this.message=statusMsg; return this; } public AppResult error(String statusMsg) { this.status="500"; this.message=statusMsg; return this; } public AppResult addData(String key,Object object) { this.data.put(key,object); return this; } }
2、创建RESTful控制器
@RestController @RequestMapping(value = "/") public class UserController { @PostMapping("/login") public AppResult login(HttpServletRequest request, HttpServletResponse response) throws Exception { return new AppResult().ok("登录成功!").addData("token", 1234); } @PostMapping("/test") public AppResult test(HttpServletRequest request, HttpServletResponse response) throws Exception { return new AppResult().ok("测试!"); } }
3、测试API
以上是关于从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统03创建RESTful API,并统一处理返回值的主要内容,如果未能解决你的问题,请参考以下文章