Struts自定义标签的过程
时间:2011-03-20
近日体验了一下Eclipse
打开某个jsp页面,页面上的select下拉列表框用Struts自定义标签来完成
1、新建页面:Test.jsp
2、在Web应用的WEB-INF目录下自定义标签TLD文件:TestTag.tld
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>dtree</shortname>
<uri>http://jakarta.apache.org/struts/tags-bean</uri>
<tag>
<name>selectResnodes</name>
<tagclass>myWeb.taglib.SelectTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>id</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>nodeslist</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>scope</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
3、在myWeb.Action包下定义AbstractResAction.java文件和TestAction.java文件(利用了java的反射机制)
AbstractResAction.java文件:
package myWeb.Action;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public abstract class AbstractResAction extends Action {
public final ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
String cmd = httpServletRequest.getParameter("actionType"); // 获取参数,其实为函数名
System.out.println("actionType = " + cmd);
if (cmd == null || cmd.equals(""))
return actionMapping.findForward("default");
try {
Method method = this.getClass()
.getMethod(
cmd,new Class[] { ActionMapping.class,
ActionForm.class, HttpServletRequest.class,
HttpServletResponse.class });
// 利用反射机制,调用method方法。而这个method方法是由页面指定的actionType定义的。
return (ActionForward) method.invoke(this, new Object[] {
actionMapping, actionForm, httpServletRequest,
httpServletResponse });
} catch (Exception e) {
e.printStackTrace();
return actionMapping.findForward("default");
}
}
}
TestAction.java文件:
package myWeb
|