## 前言
在如今前后端开发的趋势下,我们经常需要在项目中,拥有一个标准的接口数据返回格式,而AjaxResult 类即是为了提供一种统一格式的接口数据返回。
## 使用
我们只需要在方法的返回值上,设置为**AjaxResult**类即可
```
@RequestMapping("/hello")
public AjaxResult hello(HttpServletResponse httpServletResponse) throws IOException {
AjaxResult ajaxResult = new AjaxResult();
ajaxResult.put("code", 200);
ajaxResult.put("message", "消息");
ajaxResult.put("data", "hello word,hello springsecurity");
return ajaxResult;
}
```
以上为创建对象的用户,**AjaxResult**类也提供了,多个静态方法供我们使用
```
@RequestMapping("/hello")
public AjaxResult hello(HttpServletResponse httpServletResponse) throws IOException {
return AjaxResult.success(200, "message", "data");
}
```
### 提供的静态方法
```
AjaxResult.success(int code, String message, Object data)
AjaxResult.success( Object data)
AjaxResult.success(String message, Object data)
AjaxResult.success(int code, Object data)
AjaxResult.success() //默认返回200状态码
```
```
AjaxResult.error(int code, String message, Object data)
AjaxResult.error(Object data)
AjaxResult.error(String message, Object data)
AjaxResult.error(int code, Object data)
AjaxResult.error() //默认返回500状态码
```
## 源代码
```
public class AjaxResult extends HashMap<String, Object>{
private static final long serialVersionUID = 1L;
public AjaxResult() { }
public AjaxResult(int code, String message, Object data) {
super.put(AjaxResult.CODE, code);
super.put(AjaxResult.MESSAGE, message);
super.put(AjaxResult.DATA, data);
}
public final static String CODE = "code";
public final static String MESSAGE = "message";
public final static String DATA = "data";
public final static int SUCCESS = 200;
public final static int ERROR = 500;
public static AjaxResult success() {
return AjaxResult.success(AjaxResult.SUCCESS,null, null);
}
public static AjaxResult success(int code, String message, Object data) {
return new AjaxResult(code,message, data);
}
public static AjaxResult success(Object data) {
return AjaxResult.success(AjaxResult.SUCCESS,"success", data);
}
public static AjaxResult success(String message, Object data) {
return AjaxResult.success(AjaxResult.SUCCESS, message, data);
}
public static AjaxResult success(int code, Object data) {
return AjaxResult.success(code, null, data);
}
public static AjaxResult error(int code, String message, Object data) {
return new AjaxResult(code, message, data);
}
public static AjaxResult error(String message, Object data) {
return AjaxResult.error(AjaxResult.ERROR, message, data);
}
public static AjaxResult error(Object data) {
return AjaxResult.error(AjaxResult.ERROR, null, data);
}
public static AjaxResult error(int code, Object data) {
return AjaxResult.error(code, null, data);
}
public static AjaxResult error() {
return AjaxResult.error(AjaxResult.ERROR, null, null);
}
}
```