问题
I'm using Struts 2. Using an interceptor, I create a database connection at the start of each page execution.
So for example, if a user goes to "myAction.do", it will create the database connection and then call myAction.do method.
What I'm looking for now is an interceptor or any other way to automatically call a method after the page execution, which will close the database connection.
Is that possible?
回答1:
In interceptor you can write pre processing and post processing logics.
Pre processing logic will execute before the action executes and post processing logic executes after the action executes.
Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
Whatever you will write after invocation.invoke(); that will execute after executes action
SEE HERE FOR EXAMPLE
回答2:
Fully described in http://blog.agilelogicsolutions.com/2011/05/struts-2-interceptors-before-between.html
You can have interceptor:
- Before Action
- Between Action and Result
- After View Rendered
As mentioned in the site here are code samples
Before Interceptor
public class BeforeInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// do something before invoke
doSomeLogic();
// invocation continue
return invocation.invoke();
}
}
}
Between action and result
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();
}
}
}
After View Rendered
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();
}
}
}
}
来源:https://stackoverflow.com/questions/16475415/struts-2-interceptor-that-runs-after-the-page-executes