本节应用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,并统一处理返回值-LMLPHP

05-11 18:11