标签:out code request bean nts prefix har end handle
1.自定义异常类与自定义异常处理器
1).自定义异常类
/** *自定义异常类继承Exception */ public class SysException extends Exception { private String message; @Override public String getMessage() { return message; } public SysException(String message){ this.message=message; } }
2).自定义异常处理器
/** * 自定义异常处理器实现HandlerExceptionResolver接口 */ public class SysExceptionResolve implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView mv = new ModelAndView(); SysException sysException =null; if(e instanceof SysException){ sysException= (SysException) e; }else { sysException = new SysException("服务器进入二次元了"); } mv.addObject("message",sysException.getMessage()); mv.setViewName("error"); return mv; } }
2.配置自定义异常处理器和编写error友好界面
1). 在resources目录下的xml文件中配置bean
<!--配置自定义异常处理器--> <bean id="sysExceptionResolve" class="cn.itcast.controller.utils.SysExceptionResolve"></bean>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
2).编写error友好界面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>异常界面</title> </head> <body> <h3>${message}</h3> </body> </html>
3.测试结果
测试结果的前台代码
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <body> <h2>Hello World!</h2> <a href="/user/exception">Exception测试</a> </body> </html>
测试结果的后台代码
@Controller @RequestMapping("/user") public class UserController { @RequestMapping("/exception") public String testException() throws SysException { System.out.println("testException..."); try { int a = 10/0; } catch (Exception e) { e.printStackTrace(); throw new SysException("查询数据出错了"); } return "success"; } }
标签:out code request bean nts prefix har end handle
原文地址:https://www.cnblogs.com/georgeJavaEE/p/9782708.html