利用java反射读取不同的类,去onLoad加载页面对象,在页面加载的同时请求数据。
页面调用<mytag:onload msgHdr="PortalUserMsgHdr" optType="on_load" param="{aa:'21'}"/>
1.标签注册<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
version="2.0">
<display-name>JSTL core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>maokai</short-name>
<uri>/WEB-INF/mytag</uri>
<tag>
<name>onload</name>
<tag-class>com.kcityteam.utils.OnLoadTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>msgHdr</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>optType</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>param</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
2.java处理标签
public class OnLoadTag extends SimpleTagSupport{
//页面传来的三个参数,通过set方法获取
private String msgHdr;
private String optType;
private String param;
public void setMsgHdr(String msgHdr){
this.msgHdr = msgHdr;
}
public void setOptType(String optType){
this.optType = optType;
}
public void setParam(String param){
this.param = param;
}
@Override
public void doTag() throws JspException, IOException {
try {
PageContext pc = (PageContext)getJspContext();
HttpServletRequest request = (HttpServletRequest)pc.getRequest();
HttpServletResponse response = (HttpServletResponse) pc.getResponse();
//反射进入到不同的类中执行
Class aa=Class.forName("com.kcityteam.portalMsgHdr."+msgHdr);
Object test =aa.newInstance();
//调用类中的OnLoad方法,传递参数request,response
Method method=aa.getDeclaredMethod("OnLoad", new Class[]{HttpServletRequest.class,HttpServletResponse.class});
request.setAttribute("optType", optType);
request.setAttribute("param", param);
method.invoke(test,new Object[]{request,response});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
/*JSONObject ONJ=JSONObject.fromObject(param);
System.out.println(ONJ);
System.out.println(msgHdr+"--");
System.out.println(optType);
System.out.println(param);*/
//String content = "---2212";
//this.getJspContext().getOut().write(content);
}
}
3.Action层处理数据并request.setAttributes出去。页面就可以获取到值了。