因为返回都是非常固定的写法,所以应该对其进行封装。
添加ResponseUtils类
package com.wu.oa.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.Map;
public class ResponseUtils {
private String code;
private String message;
private Map data = new LinkedHashMap();
// 默认构造是成功返回的信息
public ResponseUtils() {
this.code = "0";
this.message = "success";
}
// 统一对错误的处理
public ResponseUtils(Exception exception) {
this.code = exception.getClass().getSimpleName();
this.message = exception.getMessage();
}
public ResponseUtils(String code, String message) {
this.code = code;
this.message = message;
}
// 使用setData可以链式向data添加数据
public ResponseUtils setData(String key, Object value) {
this.data.put(key, value);
return this;
}
// 重写toString,返回JSON格式的数据
@Override
public String toString() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
try {
String json = objectMapper.writeValueAsString(this);
return json;
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Map getData() {
return data;
}
public void setData(Map data) {
this.data = data;
}
}
对比
以前的写法
// 处理登录参数,未使用ResponseUtils
Map result = new LinkedHashMap<>();
try {
User user = userService.checkLogin(username, password);
Map data = new LinkedHashMap();
data.put("user",user);
result.put("code","0");
result.put("message","success");
result.put("data", data);
} catch (Exception e) {
result.put("code", e.getClass().getSimpleName());
result.put("message",e.getMessage());
}
// 返回JSON
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String json = objectMapper.writeValueAsString(result);
response.getWriter().println(json);
现在的写法
// 处理登录参数
PrintWriter writer = response.getWriter();
try {
User user = userService.checkLogin(username, password);
writer.println(new ResponseUtils().setData("user", user));
} catch (Exception e) {
writer.println(new ResponseUtils(e));
}
可见减少了很多重复代码,而且结构也更清晰了