程序级别接口返回值,异常和Error通常需要统一编码,本文以项目应用为前提,应用Spring中集成的MessageSource实现国际化,并应用BingdingResult和@Valid实现属性统一校验。实现步骤如下:
1. 根据约定建立messages.properties,与application.properties同级。
responseMsg.map.0=success
responseMsg.map.1100=server internal exception
responseMsg.map.1101=NoNodeAvailableException
responseMsg.map.1102=IllegalStateException
2. 建立统一返回Json样式类ResponseJson:
package com.springcloude.common.message;
import com.springcloude.common.plugin.Page;
import java.io.Serializable;
/**
* @author whp
* @create 2017-07-21 上午10:14
*/
public class ResponseJson implements Serializable {
public static final int SUCCESS = 0;
private static final long serialVersionUID = 1L;
private int code = 1100;
private String msg;
private Object data = null;
private long currentPage;
private long totalPage;
private long totalResults;
private long currentTotalResults;
public ResponseJson() {
}
public ResponseJson(int code, String msg) {
this.code = code;
this.msg = msg;
}
public ResponseJson(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public ResponseJson(int code, String msg, Object data, Page page) {
this.code = code;
this.msg = msg;
this.data = data;
this.totalPage = page.getTotalPage();
this.currentPage = page.getCurrentPage();
this.totalResults = page.getCurrentTotalResults();
this.currentTotalResults=page.getTotalResults();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String emsg) {
this.msg = emsg;
}
public Object getData() {
return data;
}
public long getCurrentTotalResults() {
return currentTotalResults;
}
public void setCurrentTotalResults(long currentTotalResults) {
currentTotalResults = currentTotalResults;
}
public void setData(Object data) {
this.data = data;
}
public long getCurrentPage() {
return currentPage;
}
public void setCurrentPage(long currentPage) {
this.currentPage = currentPage;
}
public long getTotalPage() {
return totalPage;
}
public void setTotalPage(long totalPage) {
this.totalPage = totalPage;
}
public long getTotalResults() {
return totalResults;
}
public void setTotalResults(long totalResults) {
this.totalResults = totalResults;
}
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
}
3. 建立Controller父类,统一控制输出内容:
package com.springcloud.server1.controller.base;
import com.springcloude.common.message.ResponseJson;
import com.springcloude.common.message.ResponseOAJson;
import com.springcloude.common.plugin.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class BaseController {
@Autowired
private MessageSource messageSource;
protected Logger logger = LoggerFactory.getLogger(BaseController.class);
public ResponseJson responseMsg(int code) {
return new ResponseJson(code, MSG(code));
}
public ResponseJson responseMsg(int code, String msg) {
return new ResponseJson(code, msg);
}
public ResponseOAJson responseOAJson(int msgCode, String msg){
return new ResponseOAJson(msgCode,msg);
}
public ResponseJson responseMsg(int code, Object data) {
return new ResponseJson(code, MSG(code), data);
}
public ResponseJson responseMsg(int code, Object data, Page page) {
return new ResponseJson(code, MSG(code), data,page);
}
/**
* 根据错误码,返回messages文件中描述信息
*/
public String MSG(int key) {
Locale currentLocale = LocaleContextHolder.getLocale();
return messageSource.getMessage("responseMsg.map." + key, null, currentLocale);
}
/**
* 实体校验跳转到错误页面
*/
public String showErrorPage(Model model, BindingResult result) {
List list = result.getFieldErrors();
List errors = new ArrayList();
for (int i = 0; i < list.size(); i++) {
FieldError fieldError = list.get(i);
errors.add(fieldError.getField() + ":" + fieldError.getDefaultMessage());
}
model.addAttribute("errors", errors);
return "error_message";
}
/**
* 字段校验失败统一编码为1016
*/
public ResponseJson showErrorJson(BindingResult result) {
FieldError error = result.getFieldErrors().get(0);
return new ResponseJson(1016, error.getField() + ":" + error.getDefaultMessage());
}
}
4. 举例应用:
@RequestMapping(value = "/update",method = RequestMethod.POST)
public ResponseJson update(@Valid User user,BindingResult result,HttpServletRequest request){
if(result.hasErrors()){
return showErrorJson(result);
}
int flag=userService.update(user);
return responseMsg(0,user);
}
该实例使用@Valid对User实体进行注解,user配置用户名校验格式:
@NotNull
@Size(min = 1, max = 100)
private String name;
请求该接口,返回值为:
{
"code": 1016,
"msg": "name:不能为null",
"data": null,
"currentPage": 0,
"totalPage": 0,
"totalResults": 0,
"currentTotalResults": 0
}