package cn.microvideo.oa.util;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
public class BindResult {
private BindResult() {
}
public static Json Br(BindingResult br, Json json) {
Json json2=json;
StringBuffer sb=new StringBuffer();
//錯誤消息返回
if (br.hasErrors()) {
for (FieldError fieldError : br.getFieldErrors()) {
sb.append(fieldError.getDefaultMessage()+",");
}
json2.setMsg(sb.deleteCharAt(sb.length()-1).toString());
json2.setSuccess(false);
return json;
}
return json2;
}
}
這裏把所有錯誤都查詢後返回,控制層方法調用BindResult,另外也可以使用springmvc3.2的新註解ControllerAdvicepackage cn.microvideo.oa.util;
/**
* view object
* @author wzy
*
*/
public class Json {
private boolean success = false;
private String msg = "";
private Object obj = null;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
使用3.2的新註解,OAException是自定義異常
package cn.microvideo.oa.controller.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
/**
* 統一異常出口
* @author wzy
*
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
@ExceptionHandler({OAException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public ModelAndView processOAException(NativeWebRequest request, OAException e) {
return new ModelAndView(jsonView,"msg",e.getMessage());
}
}
<context:component-scan base-package="cn.microvideo.oa" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
參考
http://www.tuicool.com/articles/iYfqeq
http://json20080301.iteye.com/blog/1876488
http://jackyrong.iteye.com/blog/1844080