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

Struts2异常处理机制笔记

2016-07-20 17:17 405 查看
一、通常一个页面请求到后台以后,首先到action(也就是所谓MVC的controller),在action层会调用业务逻辑service层,service层会调用持久层dao获取数据,最后执行结果汇总到action,然后通过action控制转发到指定页面,原理图如下:



二、

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>


运行结果如下图:



一点一滴积累,慢慢茁壮成长!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2.0