package com.huangliang.test.core;
public class MyException extends RuntimeException {
private String errorCode;
private String msg;
public MyException(String message) {
super(message);
}
public MyException(String errorCode, String msg) {
this.errorCode = errorCode;
this.msg = msg;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.huangliang.test.core;
public class MyResponse<T> {
private String code;
private String msg;
private String error;
private T data;
public MyResponse(T data) {
this.code = "200";
this.msg = "获取成功";
this.error = "";
this.data = data;
}
public MyResponse(String code, String msg, String error, T data) {
this.code = code;
this.msg = msg;
this.error = error;
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package com.huangliang.test.modules.user.controller;
import com.huangliang.test.core.MyException;
import com.huangliang.test.core.MyResponse;
import com.huangliang.test.modules.user.domain.User;
import com.huangliang.test.modules.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(name = "/user/list", method = RequestMethod.GET)
@ResponseBody
public MyResponse getUserList() {
List<User> list = userService.getUserList();
if (list == null) {
throw new MyException("获取对象为空");
}
return new MyResponse(list);
}
}
返回数据:
{
"code": "200",
"msg": "获取成功",
"error": "",
"data": [
{
"id": 1,
"name": "sam",
"phone": "15928005689",
"age": 22
},
{
"id": 2,
"name": "summer",
"phone": "18302895614",
"age": 25
},
{
"id": 3,
"name": "wang",
"phone": "18756894422",
"age": 24
}
]
}