Struts2异常处理机制笔记
2016-07-20 17:17
405 查看
一、通常一个页面请求到后台以后,首先到action(也就是所谓MVC的controller),在action层会调用业务逻辑service层,service层会调用持久层dao获取数据,最后执行结果汇总到action,然后通过action控制转发到指定页面,原理图如下:
![](http://img.blog.csdn.net/20160720164050108)
二、
1.Spring把大多数非运行时异常都转换成运行时异常(RuntimeException)最后导致程序员不知道在什么地方进行try…cathch操作
2.每个方法都重新try…catch,而且catch块内的代码都很相似,这明显做了很多重复工作而且人容易出错。
综上采用struts2拦截器,原理图如下:
![](http://img.blog.csdn.net/20160720164915597)
1.需要处理异常代码处:
![](http://img.blog.csdn.net/20160720165459985)
2.自定义拦截器代码
拦截器在struts.xml的配置情况
![](http://img.blog.csdn.net/20160720170829871)
这样在写个errorMsg.jsp页面就好了
运行结果如下图:
![](http://img.blog.csdn.net/20160720171616764)
一点一滴积累,慢慢茁壮成长!
二、
1.Spring把大多数非运行时异常都转换成运行时异常(RuntimeException)最后导致程序员不知道在什么地方进行try…cathch操作
2.每个方法都重新try…catch,而且catch块内的代码都很相似,这明显做了很多重复工作而且人容易出错。
综上采用struts2拦截器,原理图如下:
PS:以上参看文献地址:http://bbs.itcast.cn/thread-10364-1-1.html
以下是我自己写的代码1.需要处理异常代码处:
2.自定义拦截器代码
@Component(value="errorInterceptor") public class ErrorInterceptor implements Interceptor{ private static final long serialVersionUID = 1L; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public String intercept(ActionInvocation actioninvocation){ String result = null; try{ result = actioninvocation.invoke(); return result; }catch(Exception e){ //处理异常 String errorMsg = "出现错误信息,请查看日志!"; if(e instanceof RuntimeException ){ RuntimeException re = (RuntimeException)e; errorMsg = re.getMessage().trim(); } //把自定义错误信息发送到错误页面 HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("errorMsg", errorMsg); logger.info("ErrorInterceptor.class,errorMsg:" + errorMsg); return "errorMsg"; } } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init() { // TODO Auto-generated method stub } }
拦截器在struts.xml的配置情况
这样在写个errorMsg.jsp页面就好了
<div align="center"> <s:if test="%{#request.errorMsg==null}"> <label style="color:red;">对不起,系统发生了未知的错误,请查看日志</label><br> </s:if > <s:if test="%{#request.errorMsg!=null}"> <label style="color:red;">${requestScope.errorMsg}</label><br> </s:if> <a href="login.jsp">返回登录页</a> </div>
运行结果如下图:
一点一滴积累,慢慢茁壮成长!
相关文章推荐
- Struts - 标签库
- struts1.0于struts2.0的比较
- Struts2中关于namespace的学习心得
- Struts2----自定义action的学习心得
- HTTP Status 404 - There is no Action mapped for namespace [/] and action name [login!welcome] associ
- struts2
- SSH学习笔记---struts2 spring集成时action的class的值
- ssh--问题记录
- 文章标题 使用ajaxFileupload+struts2完成文件的上传以及回显到jsp的链接地址
- struts 学习笔记
- Struts2 的基本配置
- struts2框架架构流程
- struts2.0拦截器(实现未登录的用户不能访问系统的页面)(转)
- Struts2 面试题分析
- Struts2+jQuery+JSON实现异步交互
- 软件开发疑惑解答
- ajax ssh 整合
- 关于struts2框架学习
- struts2 @Action给方法注解
- struts2学习笔记