Reputation: 45475
Consider below action class with three action mappings. Two of them are annotated with a custom annotation @AjaxAction
public class MyAction extends ActionSupport{
@Action("action1")
@AjaxAction //My custom anotation
public String action1(){
}
@Action("action2")
public String action2(){
}
@Action("action3")
@AjaxAction //My custom anotation
public String action3(){
}
}
In an interceptor I want to access the @AjaxAction
annotation. Is there any built in support for this?!
If not can I shall read the action name with ActionContext.getContext().getName();
and save a list of ajaxAction
names in interceptor as an array and compare action name with this array! any better way?!
private static final String[] AJAX_ACTIONS = new String[] {"action1", "action3"}
//in interceptor
String actionName = ActionContext.getContext().getName();
if (Arrays.asList(AJAX_ACTIONS).contains(actionName)) {
// do something
}
Upvotes: 1
Views: 742
Reputation: 2856
Here is the way
import java.lang.reflect.Method;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class YourInterceptor implements Interceptor {
@Override
public String intercept(ActionInvocation inv) throws Exception {
Class myActionClass = inv.getAction().getClass();
for (Method method : myActionClass.getMethods())
{
if(method.isAnnotationPresent(AjaxAction.class))
{
// do something
}
}
return inv.invoke();
}
}
Alternative is
import com.opensymphony.xwork2.util.AnnotationUtils;
import java.lang.reflect.Method;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class YourInterceptor implements Interceptor {
@Override
public String intercept(ActionInvocation inv) throws Exception {
AnnotationUtils myutil = new AnnotationUtils();
Class myActionClass = inv.getAction().getClass();
for (Method method : myActionClass.getMethods())
{
if(myutil.getAnnotatedMethods(myActionClass, AjaxAction.class).contains(method))
{
// do something
}
}
return inv.invoke();
}
}
Edit :
To find exact executed method.
Note: Change Namespace="/"
as per your configuration in struts.xml
.
import org.apache.struts2.dispatcher.Dispatcher;
ActionContext context = inv.getInvocationContext();
String executedAction=context.getName();
String executedMethod=Dispatcher.getInstance().getConfigurationManager().getConfiguration().getRuntimeConfiguration().getActionConfigs().get("/").get(executedAction).getMethodName();
if(executedMethod==null)
{
executedMethod="execute";
}
for (Method method : myActionClass.getMethods())
{
if(method.getName().equalsIgnoreCase(executedMethod) || method.isAnnotationPresent(Action.class))
{
// do something
}
}
Class myActionClass = inv.getAction().getClass();
for (Method method : myActionClass.getMethods())
{
//check whether called method has annotation?
if(method.getName().equalsIgnoreCase(executedAction) && method.isAnnotationPresent(AjaxAction.class))
{
// do something
}
}
I hope this will work.
Note: This is just a workaround I found. Better way would be possible....
Upvotes: 1