创建Result工具类接收返回值
创建一个通用的Result类时,可以使用一个接口来定义返回结果的状态码
package com.common.utils;
public interface ResultCode {
public static Integer SUCCESS = 200; //成功
public static Integer ERROR = 400; //失败
}
创建Result工具类
package com.common.utils;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
//统一返回结果的类
public class Result {
private Boolean success;
private Integer code;
private String state;
private Map<String, Object> data = new HashMap<String, Object>();
//把构造方法私有
private Result() {}
//成功静态方法
public static Result ok() {
Result r = new Result();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setState("成功");
return r;
}
//失败静态方法
public static Result error() {
Result r = new Result();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setState("失败");
return r;
}
public Result success(Boolean success){
this.setSuccess(success);
return this;
}
public Result state(String state){
this.setState(state);
return this;
}
public Result code(Integer code){
this.setCode(code);
return this;
}
public Result data(String key, Object value){
this.data.put(key, value);
return this;
}
public Result data(Map<String, Object> map){
this.setData(map);
return this;
}
}
工具类的使用示例:
public Result login(String username){
List<User> list = userMapper.selectByname(username);
if (!list.isEmpty()) {
String token = JwtUtils.generateToken(username);
return Result.ok().data("token",token).data("message","登陆成功");
} else {
return Result.error().data("message","用户名或密码错误");
}
}