您的位置:首页 > 编程语言 > Java开发

spring mvc4 全局异常处理

2015-08-31 00:00 615 查看
摘要: spring mvc @ControllerAdvice 的一些简单用法

异常拦截控制器

@ControllerAdvice
public class ExceptionControllerAdvice {

@ExceptionHandler(Exception.class)
public ModelAndView exception(Exception e) {          //普通的请求可以这样拦截
ModelAndView mav = new ModelAndView("error/exception");
mav.addObject("name", e.getClass().getSimpleName());
mav.addObject("message", e.getMessage());
return mav;
}
@ExceptionHandler(AjaxException.class)
public void Ajaxexception(Exception e, HttpServletResponse response) { //用于拦截ajax的请求
Map<String,Object> map=new HashMap<String, Object>();
map.put("name", e.getClass().getSimpleName());
map.put("message", e.getMessage());
JsonUtil.writeJsonData(map, response);
}
}


自定义ajax异常类

public class AjaxException extends Exception {    //自定义ajax异常
public AjaxException(String message) {
super(message);
}
public AjaxException() {
super();
}
}


将对象处理成json

这里使用的是alibaba的fastjson

fastjson的 POM.XML配置

<!-- fastJSON包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.22</version>
</dependency>

/**
* 将数据以JSon的形式写入PrintWriter中的工具类
* @author Evil
*/
public class JsonUtil {

public static void writeJsonData(Object object,HttpServletResponse response) {
try {
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(JSONArray.toJSONString(object));
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


测试

控制器

@Controller
@RequestMapping(produces = ("text/html;charset=UTF-8"))
public class TestController {
@RequestMapping("test.do")
public  String test() throws Exception{
if(true){
throw new IOException("this is io exception");
}
return null;
}
@RequestMapping("ajaxTest.do")
public  String ajaxTest() throws AjaxException{
if(true){
throw new AjaxException("this is io exception");
}
return null;
}
}


访问test.do

Ops! Something went wrong

IOException: this is io exception

访问呢ajaxTest.do

{"message":"this is io exception","name":"AjaxException"}

spring mvc 全局控制器完成
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息