考虑以下具有三个动作映射的动作类。其中两个使用自定义注释@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(){
}
}
在拦截器中,我想访问@AjaxAction
注释。有没有内置的支持?!
如果没有,我可以用ActionContext.getContext().getName();
读取动作名称,并将拦截器中的ajaxAction
名称列表保存为数组,并将动作名称与此数组进行比较!有更好的方法吗?!
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
}
答案 0 :(得分:1)
这是方式
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();
}
}
替代方案是
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();
}
}
修改:
找到确切执行的方法。
注意:根据Namespace="/"
中的配置更改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
}
}
我希望这会奏效。
注意:这只是我找到的解决方法。 更好方式可能......