JSP自定义标签
实际使用:
<td style="text-align: center;">
<b:Call type="com.techson.util.DateUtil" method="dateToStr" var="checkin">
<b:Param paramclass="java.util.Date" value="${vo.checkin}" />
<b:Param paramclass="java.lang.String" value="@dd@-@MMM@-@yy@" />
</b:Call>
${checkin}
</td>
输出的日期是Date类型,在dateToStr方法中将其格式化并转化为String类型显示,如

标签引入:
<%@ taglib uri="/WEB-INF/utils.tld" prefix="b"%>
utils.tld:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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">
<tlib-version>1.0</tlib-version>
<short-name>utils</short-name>
<uri>/WEB-INF/utils</uri>
<tag>
<name>Call</name>
<tag-class>tags.Call</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>bean</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.Object</type>
</attribute>
<attribute>
<name>type</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>method</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>var</name>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>scope</name>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<dynamic-attributes>true</dynamic-attributes>
</tag>
<tag>
<name>Param</name>
<tag-class>tags.ParamTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>paramclass</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.Object</type>
</attribute>
</tag>
</taglib>
tags.ParamTag.java类:
package tags;
import javax.servlet.jsp.JspException;
public class ParamTag extends SimpleTagSupport {
private java.lang.String _class;
private java.lang.Object value;
public void doTag() throws JspException {
StrictTypeParams parent = (StrictTypeParams)findAncestorWithClass(this, StrictTypeParams.class);
//调用父标签,即b:call
if (parent == null) {
throw new JspException("The Param tag is not enclosed by a supported tag type");
}
parent.addStrictTypeParameter(this._class, this.value);
//addStr..是父标签中方法
}
/**
* Setter for the class attribute.
*/
public void setParamclass(java.lang.String value) {
this._class = value;
}
public void setValue(java.lang.Object value) {
this.value = value;
}
}
StrictTypeParams:一个引用父标签的接口
package tags;
public interface StrictTypeParams {
void addStrictTypeParameter(String type, Object value);
}
tags.Call.java类:
* Call.java
package tags;
import java.lang.reflect.Method;
public class Call extends SimpleTagSupport implements DynamicAttributes, StrictTypeParams {
/**
* Initialization of bean property.
*/
private java.lang.Object bean;
private java.lang.String type;
private java.lang.String method;
private java.lang.String var = null;
private int scope = PageContext.PAGE_SCOPE;
private List dynamicAttrValues = new ArrayList();
private List typeList = null;
//doTag()为标签默认执行方法
public void doTag() throws JspException {
JspWriter out=getJspContext().getOut();
try {
JspFragment f=getJspBody();
if (f != null) f.invoke(out);
} catch (java.io.IOException ex) {
throw new JspException(ex.getMessage());
}
boolean isStaticMethod = this.type!=null?true:false;
Class cls = null;
if(isStaticMethod){
try {
cls = Class.forName(this.type);
} catch (ClassNotFoundException e1) {
throw new JspException("Class not be found for your type!");
}
}else{
cls = bean.getClass();
}
Method[] methods = cls.getMethods();
Method m = null;
Class[] paramTypes = null;
Method : for (int i = 0; i < methods.length; i++ ) {
Method t = methods[i];
paramTypes = t.getParameterTypes(); //这个方法的参数类型的集合
if (t.getName().equals(method) && paramTypes.length == dynamicAttrValues.size()) {
if (typeList != null){
for (int j = 0; j < paramTypes.length; j++){
if (!paramTypes[j].getName().equals(typeList.get(j))){
continue Method;
}
}
}
m = t;
break;
}
}
if (m == null)
throw new JspException("JavaBean Object hasn't no method named '" + method + "'");
try {
Object coercedValues[] = new Object[paramTypes.length];
Iterator paramIterator = dynamicAttrValues.iterator();
for (int i = 0; i < paramTypes.length; i++) {
Object paramValue = paramIterator.next();
Class paramClass = paramTypes[i];
if (paramValue == null || paramValue.getClass() != paramClass)
try {
paramValue = Coercions.coerce(paramValue, paramClass, null);
} catch (ELException e) {
throw new JspException(e.getMessage(), e.getRootCause());
}
coercedValues[i] = paramValue;
}
Object returnVal = null;
if(isStaticMethod){
returnVal = m.invoke(null, coercedValues);
}else{
returnVal = m.invoke(bean, coercedValues);
}
if (var != null)
if (returnVal != null)
getJspContext().setAttribute(var, returnVal, scope);
else
getJspContext().removeAttribute(var, scope);
} catch (Exception ex) {
ex.printStackTrace();
throw new JspException("Call method is Error!");
}
}
/**
* Setter for the bean attribute.
*/
public void setBean(java.lang.Object value) throws JspException {
if (value == null)
throw new JspException("Null 'bean' attribute in 'Call' tag");
this.bean = value;
}
/**
* Setter for the method attribute.
*/
public void setMethod(java.lang.String value) throws JspException {
if (value == null)
throw new JspException("Null 'method' attribute in 'Call' tag");
this.method = value;
}
/**
* Setter for the var attribute.
*/
public void setVar(java.lang.String value) throws JspException {
if (value == null)
throw new JspException("Null 'var' attribute in 'Call' tag");
this.var = value;
}
/**
* Setter for the scope attribute.
*/
public void setScope(java.lang.String value) {
if (value.equalsIgnoreCase("page"))
scope = PageContext.PAGE_SCOPE;
else if (value.equalsIgnoreCase("request"))
scope = PageContext.REQUEST_SCOPE;
else if (value.equalsIgnoreCase("session"))
scope = PageContext.SESSION_SCOPE;
else if (value.equalsIgnoreCase("application"))
scope = PageContext.APPLICATION_SCOPE;
}
public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {
dynamicAttrValues.add(value);
}
public void addStrictTypeParameter(String type, Object value) {
if (typeList == null)
typeList = new ArrayList();
typeList.add(type);
dynamicAttrValues.add(value);
}
public void setType(java.lang.String type) {
this.type = type;
}
public static void main(String[] agrs) throws ClassNotFoundException, JspException{
String type = "com.techson.util.DateUtil";
String method="dateDiff";
List dynamicAttrValues = new ArrayList();
List typeList = new ArrayList();
typeList.add("java.lang.Boolean");
dynamicAttrValues.add(true);
Class cls = Class.forName(type);
Method[] methods = cls.getMethods();
Method m = null;
Class[] paramTypes = null;
Method : for (int i = 0; i < methods.length; i++ ) {
Method t = methods[i];
paramTypes = t.getParameterTypes();
if (t.getName().equals(method) && paramTypes.length == dynamicAttrValues.size()) {
if (typeList != null){
for (int j = 0; j < paramTypes.length; j++){
if (!paramTypes[j].getName().equals(typeList.get(j))){
continue Method;
}
}
}
m = t;
break;
}
}
if (m == null)
throw new JspException("JavaBean Object hasn't no method named '" + method + "'");
try {
Object coercedValues[] = new Object[paramTypes.length];
Iterator paramIterator = dynamicAttrValues.iterator();
for (int i = 0; i < paramTypes.length; i++) {
Object paramValue = paramIterator.next();
Class paramClass = paramTypes[i];
System.out.println(paramClass);
if (paramValue == null || paramValue.getClass() != paramClass)
try {
System.out.println(paramValue.getClass() + "/ "+ paramClass);
paramValue = Coercions.coerce(paramValue, paramClass, null);
} catch (ELException e) {
throw new JspException(e.getMessage(), e.getRootCause());
}
coercedValues[i] = paramValue;
}
Object returnVal = null;
returnVal = m.invoke(null, coercedValues);
System.out.print(returnVal);
} catch (Exception ex) {
ex.printStackTrace();
throw new JspException("Call method is Error!");
}
}
}
处理方法DateUtils.java中方法dateToStr:
public static String dateToStr(Calendar cal , String format) {
if(format.contains("@y")){
int _y = cal.get(Calendar.YEAR);
String _yyyy = new DecimalFormat("0000").format(_y);
String _yy = _yyyy.substring(2);
format = format.replaceAll("@[y]{4}@",_yyyy)
.replaceAll("@[y]{2}@",_yy)
.replaceAll("@[y]{1}@","" + _y);
}
if(format.contains("@M")){
int _M= cal.get(Calendar.MONTH) + 1;
String _MM = (_M<10)?"0"+_M:"" + _M;
String _MMM = Constants.MTH[_M - 1];
format=format.replaceAll("@MMM@",_MMM);
format=format.replaceAll("@MM@",_MM);
format=format.replaceAll("@M@","" + _M);
}
if(format.contains("@d")){
int _D= cal.get(Calendar.DATE);
String _DD=(_D<10)?"0"+_D:""+_D;
format=format.replaceAll("@dd@",_DD);
format=format.replaceAll("@d@","" +_D);
}
if(format.contains("@h")){
int _h=cal.get(Calendar.HOUR_OF_DAY);
String _hh=(_h<10)?"0"+_h:"" +_h;
format=format.replaceAll("@hh@",_hh);
format=format.replaceAll("@h@","" + _h);
}
if(format.contains("@m")){
int _m=cal.get(Calendar.MINUTE);
String _mm=(_m<10)?"0"+_m:""+_m;
format=format.replaceAll("@mm@",_mm);
format=format.replaceAll("@m@","" + _m);
}
if(format.contains("@s")){
int _s=cal.get(Calendar.SECOND);
String _ss=(_s<10)?"0"+_s:"" + _s;
format=format.replaceAll("@ss@",_ss);
format=format.replaceAll("@s@","" + _s);
}
if(format.contains("@W")){
int _W=cal.get(Calendar.DAY_OF_WEEK);
format=format.replaceAll("@WWW@",Constants.WEEK[_W-1]);
format=format.replaceAll("@WW@",Constants.WEK[_W-1]);
format=format.replaceAll("@W@","" + (_W-1));
}
return format;
}
public static String dateToStr(Date d , String format) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return dateToStr(cal,format);
}
参考:http://zengsun.iteye.com/category/25493?show_full=true
http://www.ibm.com/developerworks/cn/java/j-lo-jsp2tag/index.html?ca=drs-
http://blog.csdn.net/zavens/article/details/1685615
findAncestorWithClass:
http://www.ibm.com/developerworks/cn/java/j-taglib/
getParameterTypes: