springboot+jQuery
统一是为了提高代码的韧性,提高前后端传参的一致性,后期也有利于维护
一、创建实体
1.vo
1.ReturnBean
package cn.gsm.demo01.entity.vo;
public class ReturnBean {
private boolean success;
private String message;
private Object data;
private ReturnBean() {
}
public static ReturnBean ofReturnBean(boolean success,String message){
ReturnBean returnBean = new ReturnBean();
returnBean.setMessage(message);
returnBean.setSuccess(success);
return returnBean;
}
//重载
public static ReturnBean ofReturnBean(boolean success,String message,Object data){
ReturnBean returnBean = ofReturnBean(success, message);
returnBean.setData(data);
return returnBean;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
2.PageBean
package cn.gsm.demo01.entity.vo;
import java.util.List;
public class PageBean<T> {
private List<T> list;
private long count;
private int pageCount;//总页数
private int page;//当前页
private int size;//条数
private PageBean() {
}
public static PageBean ofPage(int page,int size){
PageBean pageBean = new PageBean();
pageBean.setPage(page);
pageBean.setSize(size);
return pageBean;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
2.全局异常处理
放在controller层
@ExceptionHandler可以理解为:异常拦截器
例如:controller中修改:
throw new RuntimeException("id不能为空");运行时异常
具体异常参考图:
package cn.gsm.demo01.controller;
import cn.gsm.demo01.entity.vo.ReturnBean;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
//全局异常处理
@ControllerAdvice
@ResponseBody
public class PublicControllerAdvice {
//异常拦截器
@ExceptionHandler(Exception.class)
public ReturnBean myExceptionHandler(Exception e){
e.printStackTrace();//打印错误
return ReturnBean.ofReturnBean(false,e.getMessage());
}
}