<error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/views/error/throwable.jsp</location> </error-page>
<!-- 将Controller抛出的异常转到特定视图 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 不同异常分开跳转-->
<!-- 可以自定义不同的异常-->
<prop key="com.test.MyException1">/error/e1</prop>
<prop key="com.test.MyException2">/error/e2</prop>
<!-- 如果不想自定义异常,只配置下面的即可-->
<prop key="java.lang.Throwable">/error/500</prop>
</props>
</property>
</bean>
/**
* 自定义异常处理器:支持ajax
* @author wangxu
*
*/
public class MyExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
/* 区分ajax */
boolean isAjax = request.getHeader("X-Requested-With") != null
&& "XMLHttpRequest".equals(request
.getHeader("X-Requested-With").toString());
if (!isAjax) {
if (ex instanceof com.test.MyException1) {
return new ModelAndView("/error/e1");
} else if (ex instanceof com.test.MyException1) {
return new ModelAndView("/error/e2");
} else {
return new ModelAndView("/error/500");
}
}
String jsonRes = "{\"message\":\"" + "系统异常" + "\"}";// 自定义结构和前台对接
PrintWriter out = null;
try {
out = response.getWriter();
request.setCharacterEncoding("utf-8");
response.setContentType("text/plain;charset=utf-8");
out.print(jsonRes);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
}
return null;
}
}
@Controller
public class TestExceptionHandlerController {
@ExceptionHandler({ MyException1.class })
public String exception(MyException1 e) {
return "/error/e1";
}
@RequestMapping("/marry")
public void test() {
throw new MyException1("没钱!");
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有