【发布时间】:2013-05-10 04:55:45
【问题描述】:
我正在使用 Struts 2。使用拦截器,我在每个页面执行开始时创建一个数据库连接。
例如,如果用户访问“myAction.do”,它将创建数据库连接,然后调用myAction.do方法。
我现在正在寻找的是一个拦截器或任何其他在页面执行后自动调用方法的方式,这将关闭数据库连接。
这可能吗?
【问题讨论】:
标签: java struts2 interceptor
我正在使用 Struts 2。使用拦截器,我在每个页面执行开始时创建一个数据库连接。
例如,如果用户访问“myAction.do”,它将创建数据库连接,然后调用myAction.do方法。
我现在正在寻找的是一个拦截器或任何其他在页面执行后自动调用方法的方式,这将关闭数据库连接。
这可能吗?
【问题讨论】:
标签: java struts2 interceptor
在拦截器中你可以编写预处理和后处理逻辑。
预处理逻辑将在动作执行之前执行,并且 后处理逻辑在动作执行后执行。
Struts2 提供了非常强大的请求控制机制 使用拦截器。拦截器负责大部分 请求处理。它们由控制器调用之前和 在调用动作之后,它们位于控制器和 行动。拦截器执行诸如日志记录、验证、文件等任务 上传、双重提交保护等。
无论你在invocation.invoke();之后写什么,都会在执行动作之后执行
【讨论】:
intercept()叫做预处理,但是什么方法叫做后处理呢? destroy() 是否总是为每个请求调用后处理,还是偶尔调用一次?
invocation.invoke() 之前运行myAction.setSomeValue(),你知道怎么做吗?
(MyAction) action = invocation.getAction(),然后运行action.setSomeValue()
完整描述在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();
}
}
}
}
【讨论】: