jsp 自定义标签的使用
jsp中的引用
<%@taglib prefix="f" uri="http://www.jee-soft.cn/functions" %> web.xml中的配置 <taglib> <taglib-uri>http://www.jee-soft.cn/functions</taglib-uri> <taglib-location>/WEB-INF/tld/HtTag.tld</taglib-location> </taglib>
xxx.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>f</short-name> <uri>http://www.jee-soft.cn/functions</uri> <function> <description>取得当前日期</description> <name>currentDate</name> <function-class>com.hotent.core.util.TimeUtil</function-class> <function-signature>java.lang.String getCurrentDate()</function-signature> <example>${f:currentDate()}</example> </function> <tag> <name>validjs</name> <description>JS验证标签</description> <tag-class>com.hotent.core.web.tag.ValidJsTag</tag-class> <body-content>JSP</body-content> <attribute> <name>formName</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
java类
一般实现的类,要继承BodyTagSupport 类
package com.hotent.core.web.tag; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hotent.core.util.ContextUtil; /** * 用于实现个性化皮肤。<br/> * <pre> * 使用方法如下: * * <f:link href="web.css" ></f:link> * </pre> * */ @SuppressWarnings("serial") public class StyleTag extends BodyTagSupport { protected Logger logger = LoggerFactory.getLogger(StyleTag.class); private String href; public String getHref() { return href; } public void setHref(String href) { this.href = href; } public int doStartTag() throws JspTagException { return EVAL_BODY_BUFFERED; } private String getOutput() throws Exception { HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); logger.info(request.getRequestURI()); StringBuffer content = new StringBuffer("<link title=\"index\" name=\"styleTag\" rel=\"stylesheet\" type=\"text/css\" href=\""); content.append(request.getContextPath()); content.append("/styles/"); String styleName=ContextUtil.getCurrentUserSkin(request); //MyProfile myProfile = UserHelper.getProfile(request); // if(myProfile != null && myProfile.getSkin() != null) { // content.append(myProfile.getSkin()); // } else { content.append(styleName+"/css"); // } content.append("/"); content.append(href); content.append("\"></link>"); return content.toString(); } public int doEndTag() throws JspTagException { try { String str = getOutput(); pageContext.getOut().print(str); } catch (Exception e) { throw new JspTagException(e.getMessage()); } return SKIP_BODY; } }