我正在使用Struts 2.使用拦截器,我在每个页面执行开始时创建一个数据库连接。在页面执行后运行的Struts 2拦截器?
例如,如果用户转到“myAction.do”,它将创建数据库连接,然后调用myAction.do
方法。
我正在寻找的是一个拦截器或其他任何方式来自动调用页面执行后的方法,这将关闭数据库连接。
这可能吗?
我正在使用Struts 2.使用拦截器,我在每个页面执行开始时创建一个数据库连接。在页面执行后运行的Struts 2拦截器?
例如,如果用户转到“myAction.do”,它将创建数据库连接,然后调用myAction.do
方法。
我正在寻找的是一个拦截器或其他任何方式来自动调用页面执行后的方法,这将关闭数据库连接。
这可能吗?
在拦截器中,您可以编写预处理和后处理逻辑。
预处理逻辑将在执行动作之前执行,并且在执行动作之后执行后处理逻辑。
Struts2提供了非常强大的使用拦截器控制请求 的机制。拦截器负责大部分请求处理。它们在调用动作之前由控制器调用,因此它们位于控制器和 动作之间。拦截器执行任务,如日志记录,验证,文件上传 ,双后卫等提交
不管你会invocation.invoke();
会后执行动作
在http://blog.agilelogicsolutions.com/2011/05/struts-2-interceptors-before-between.html充分说明执行后写
你可以有拦截器:
经过此处的相关网站中提到的代码示例
拦截
之前public class BeforeInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// do something before invoke
doSomeLogic();
// invocation continue
return invocation.invoke();
}
}
}
行动和结果之间
public class BetweenActionAndResultInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// Register a PreResultListener and implement the beforeReslut method
invocation.addPreResultListener(new PreResultListener() {
@Override
public void beforeResult(ActionInvocation invocation, String resultCode) {
Object o = invocation.getAction();
try{
if(o instanceof MyAction){
((MyAction) o).someLogicAfterActionBeforeView();
}
//or someLogicBeforeView()
}catch(Exception e){
invocation.setResultCode("error");
}
}
});
// Invocation Continue
return invocation.invoke();
}
}
}
视图中呈现
public class AfterViewRenderedInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// do something before invoke
try{
// invocation continue
return invocation.invoke();
}catch(Exception e){
// You cannot change the result code here though, such as:
// return "error";
// This line will not work because view is already generated
doSomeLogicAfterView();
}
}
}
}
据我所知,'拦截()'被称为预处理后,但什么方法被称为后处理?对于每个请求,“destroy()”总是被称为后处理,或者只是偶尔一次? – 2013-05-10 05:02:29
看到我更新了我的答案 – PSR 2013-05-10 05:03:49
太棒了,非常感谢。我会尽快接受你的回答。还有一个问题,如果我想运行一个自定义的动作方法,例如,如果我想在'invocation.invoke()'之前运行'myAction.setSomeValue()',你知道怎么做? – 2013-05-10 05:08:19