方法1
package com.itcast.utils;
import java.util.HashMap;
import java.util.Map;
/**
* 返回通用的类
*/
public class Msg {
//状态码100-成功
//200-失败
private int code;
//提示信息
private String msg;
//用户要返回浏览器的数据
private Map<String, Object> extend = new HashMap<String, Object>();
public static Msg success() {
Msg result = new Msg();
result.setCode(100);
result.setMsg("处理成功");
return result;
}
public static Msg fail() {
Msg result = new Msg();
result.setCode(200);
result.setMsg("处理失败");
return result;
}
public Msg add(String key,Object value){
this.getExtend().put(key,value);
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, Object> getExtend() {
return extend;
}
public void setExtend(Map<String, Object> extend) {
this.extend = extend;
}
}
用法
@RequestMapping("/list1")
@ResponseBody
public Msg page( Emp emp, Integer pageNum, Integer pageSize, Model model){
PageInfo<Emp> pageInfo = empService.getEmpInfo(emp,pageNum,pageSize);
model.addAttribute("pageInfo", pageInfo);
model.addAttribute("emp", emp);
return Msg.success().add("pageInfo",pageInfo);
}
方法2
package com.itcast.utils;
public class GlobalResult {
private int code;
private String msg;
private Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
private GlobalResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static GlobalResult of(int code, String msg, Object data) {
return new GlobalResult(code, msg, data);
}
public static GlobalResult of(int code, String msg) {
return of(code, msg, null);
}
public static GlobalResult of(int code) {
return of(code, "");
}
public static GlobalResult ok() {
return ok("ok");
}
public static GlobalResult ok(String msg) {
return ok(msg, null);
}
public static GlobalResult ok(String msg, Object data) {
return of(200, msg, data);
}
public static GlobalResult error(String msg, Object data) {
return of(500, msg, data);
}
public static GlobalResult error(String msg) {
return error(msg, null);
}
public static GlobalResult error() {
return error("error");
}
}
用法
@RequestMapping("/login")
@ResponseBody
public GlobalResult tologin(@RequestBody User user, HttpServletRequest request) {
User login = userService.login(user);
if (null != login) {
request.getSession().setAttribute("user",user);
return GlobalResult.ok();
} else {
LogUtil.log("登录失败,信息错误!!!");
return GlobalResult.error("登录失败,信息错误!!!");
}
}}