struts2 进阶--异常捕获机制

在SpringMvc中有自己的异常处理机制,struts2当然会有此功能,主要是在struts.xml中配置:

<bean type="com.opensymphony.xwork2.ActionEventListener" class="com.cml.action.listener.MyActionEventListener" />

class为我们自己实现的bean,自己实现的类需要实现接口:ActionEventListener

有了异常捕获机制后,就可以在action中抛出异常后进行对应的逻辑操作或是系统日志记录!

主要代码:


public class MyActionEventListener implements ActionEventListener
{


public MyActionEventListener()
{
log.debug("Am a new ActionListener!");
}


private Logger log = Logger.getLogger("root");

//抛出异常后调用此方法
public String handleException(Throwable t, ValueStack stack)
{
if (t instanceof RuntimeException)
{
// 进行需要的处理
log.debug("action抛出异常啦!"+stack.findString("username"));
}
log.debug("抛出异常!");
return "input";
}


@Override
public Object prepare(Object target, ValueStack stack)
{
log.debug("获取stack值:" + stack.findString("name") + ":"
+ target.getClass().getName());
System.out.println("获取stack值:" + stack.findString("username"));
return target;
}
}

 ValueStack stack为struts2的值栈!

target是访问的action对象!在prepare方法中可以为我们的action类添加一些业务逻辑或判断信息!


posted @ 2014-04-20 20:41  小小架构师  阅读(124)  评论(0编辑  收藏  举报