@Response注解使用后,将不会走spring的视图解析器,效果等同于通过response对象输出指定格式的数据。
现在有一个需求,定义一个可以同时处理ajax请求异常和页面跳转异常的方法。
返回类型用ModelandView,String都不方便,也不能加@Response注解,
所以返回类型用void,通过最原始的servlet代码完成页面跳转或者返回json数据。
@ControllerAdvice
public class ImmocExceptionHandler {
public static final String ERROR_VIEW = "error";
@Autowired
private Gson gson;
@ExceptionHandler(value = Exception.class)
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response,
Exception e, Model model) throws Exception {
if (isAjax(request)) {
// 向response中写json数据
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(gson.toJson(JsonResult.errorException(e.getMessage())));
} else {
request.setAttribute("exception", e);
request.setAttribute("url", request.getRequestURL());
request.getRequestDispatcher("/templates/error.html").forward(request,
response);
}
}
public static boolean isAjax(HttpServletRequest httpRequest) {
return (httpRequest.getHeader("X-Requested-With") != null
&& "XMLHttpRequest"
.equals(httpRequest.getHeader("X-Requested-With").toString()));
}
}