struts2根据action中的方法参数值来动态调用方法

struts2 根据action中的方法参数值来动态调用方法,例如http://localhost:8080/login.do?method=dynamicMethod

根据method参数来调用action中的dynamicMethod 方法,主要是自定义拦截器来实现,代码如下

package com.tedonl.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class DynamicMethodInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -2341874790105032740L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String myMehtod = request.getParameter("mehtod");
		if (myMehtod != null) {
			try {
				java.lang.reflect.Method method = invocation.getAction().getClass().getMethod(myMehtod);
				String result = (String) method.invoke(invocation.getAction());
				if (result != null) {
					return result;
				} else {
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return invocation.invoke();
	}

}

 然后在web.xml中配置上自己的拦截器即可

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="login" namespace="/login" extends="json-default">
		<interceptors>
			<interceptor name="MyInterceptor" class="com.tedonl.interceptor.DynamicMethodInterceptor"></interceptor>
			<interceptor-stack name="MyDefaultStack">
				<interceptor-ref name="MyInterceptor" />
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="MyDefaultStack"></default-interceptor-ref>
		<action name="login" class="loginAction">
			<result name="success">/index.jsp</result>
			<result name="index">/index.jsp</result>
			<result name="conmpanyTrain">/companyTrain/sec_companyTrain.jsp</result>
		</action>

		<action name="register_*" class="registerAction" method="{1}">
			<result name="success" type="json" />
		</action>
	</package>
</struts>
 

你可能感兴趣的:(struts2)