通常情况下,会使用Struts2的异常框架对系统中产生的异常进行统一处理,其好处是可以让开发人员减少程序成中的try catch块,更多的关于业务处理,并且可以通过global与局部异常的配合使用,达到理想的效果。
当使用了这种方式之后,其异常可以指向一个result,该result可以显示为一个jsp页面,在该页面中可以友好的显示异常信息,通常显示异常可以由以下Struts标签完成:
<s:propertyvalue="exception.message"/>
以上方式基本满足异常的处理,但有些情况下,业务上需要处理更多的信息,一个简单的异常页面不能够满足需求。这时,我们更希望该异常捕获后,result能够定位到一个Action,由此Action进行后续操作。
要实现这种效果,可以在捕获异常的result中,使用chain类型的result进行处理。
在处理的Action中以下述方式获取异常信息:
ActionContext.getContext().getValueStack().findValue("exception")
示例:加入有一个接口系统,所有对外的接口均以XML作为结果输出,异常使用Struts2的统一异常框架进行处理。其实现方式如下:
在Struts2的配置文件中定义异常的处理方式(全局Exception示例):
<global-results>
<resultname="all"type="chain">error</result>
</global-results>
<global-exception-mappings>
<exception-mappingresult="all"exception="java.lang.Exception"/>
</global-exception-mappings>
<actionname="error"class="com.ray.action.ErrorAction">
<resultname="xmlMessage"></result>
</action>
当接口中发生了异常,此时无法将正确的结果返回给客户端,需要将操作失败的信息返回给用户(以定义的错误XML接口返回),同时将异常信息记录到日志中,ErrorAction的操作大致如下所示:
public String execute() {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Controll", "no-cache");
PrintWriter pw = null;
try{
pw = response.getWriter();
} catch(IOException e) {
e.printStackTrace();
}
pw.write("<result>"
+ ActionContext.getContext().getValueStack()
.findValue("exception") + "</result>");
pw.close();
return "xmlMessage";
}
Struts2中将global-exception定位到一个Action中处理,及获取其异常信息的方法
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
一个简洁、干净的中后台管理模板
nova-admin —— 一个基于Vue3、Vite5、Typescript、Naive UI, 简洁干净后台管理模板。
后台管理 后台管理模板 vue node.js npm -
在Unity中制作一个可开关的灯
在Unity中制作一个可开关的灯
UI 开关按钮 Unity -
Struts2中的Action 调度
多数的MVC框架中的Control层,都是一个Java对象。按照
Web 执行环境 数据环境 -
struts2捕获action类异常
首先是STRUTS.XML的配置,重点在于配置文件: /error.jsp这样一
struts System java -
struts2中action之间的跳转
struts2中action之间的跳转
struts action