SSM框架中封装后端返回的Json数据

①首先需要一个封装类(泛型类)
/**
* 封装后端返回的Json数据
*/

//保证序列化json时,如果是null的对象,key也会消失
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ServerResponse<T> {

//状态码
private int statu;
//数据
private T data;
//描述信息
private String msg;

//setter、getter方法
public int getStatu() {
return statu;
}

public void setStatu(int statu) {
this.statu = statu;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
//构造函数
/**
* 操作成功时,返回数据
* @param statu
* @param data
* @param msg
*/
public ServerResponse(int statu, T data, String msg) {
this.statu = statu;
this.data = data;
this.msg = msg;
}

public ServerResponse(int statu) {
this.statu = statu;
}

/**
* 操作失败时,不返回数据
* @param statu
* @param msg
*/
public ServerResponse(int statu, String msg) {
this.statu = statu;
this.msg = msg;
}

//使之不在序列化结果中
@JsonIgnore
public boolean checkIsSuccess(){
return this.statu==ResponseCode.SUCCESS.getCode();
}
//泛型方法

/**
* 成功返回数据
* @param msg
* @param data
* @param
* @return
*/
public static <T> ServerResponse<T> createBySuccess(String msg,T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data,msg);
}

/**
* 用于校验登录信息
* @param
* @return
*/
public static <T> ServerResponse<T> createByCheckSuccess(){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
}

/**
* 返回错误信息
* @param msg
* @param
* @return
*/
public static <T> ServerResponse<T> createByError(String msg){
return new ServerResponse<T>(ResponseCode.ERROR.getCode(),msg);
}

public static <T> ServerResponse<T> createByNeedLogin(){
return new ServerResponse<T>(ResponseCode.NEED_LOG.getCode(),"请先登录!");
}
}
②将常量写成一个枚举类
/**
* 定义响应的状态码
*/
public enum ResponseCode {
SUCCESS(100,"SUCCESS"),
ERROR(101,"ERROR"),
NEED_LOG(1,"NEED_LOG");
private int code;
private String desc;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}

ResponseCode(int code, String desc) {
this.code = code;
this.desc = desc;
}
}
③当有数据返回时,service层,controller层返回的数据类型为以上这个封装类
   以显示所有学生信息为例,service层:
/**
* 这时可以指定具体的封装类的泛型类型
* @return
*/
@Override
public ServerResponse> showAllStudent() {
//DAO层查询数据
List studentList = studentDao.showAllStudent();
if (studentList.size()>0){
return ServerResponse.createBySuccess("查询成功",studentDao.showAllStudent());
}
return ServerResponse.createByError("查询记录为空");
}
controller层:
@RequestMapping(value = "/showStudents")
@ResponseBody
public ServerResponse showAllStudent(HttpSession session){
//登录校验
ServerResponse serverResponse = CheckRole.checkIsLoginAndAdmin(session);
//校验成功
if (serverResponse.checkIsSuccess()){
return studentService.showAllStudent();
}
return serverResponse;
}
登录校验:参考我的博客:SSM框架中基于session的登录校验
测试:
SSM框架中封装后端返回的Json数据_第1张图片


你可能感兴趣的:(SSM)