自定义jsp标签

以对字符串中特殊符号的过滤为例,说明自定义jsp的步骤:
1、创建自定义标签类,也就是标签实际执行的方法

package myTags;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
public class JSFilterTag extends TagSupport{

	private static final long serialVersionUID = 641731803483920099L;
	
	private Object property;

	public int doStartTag() throws JspException {
	     if(property != null){	    	 
	    	 try{
	    		 //将特殊标签都替换成‘*’
	    		 String str = ((String)property).replaceAll("[\"\'<>]", "*");
	    		 pageContext.getOut().print(str);
	    	 } catch (IOException ex) {
	    		 throw new JspException(ex.getMessage());
	    	 }	    	 
	     }
	     return SKIP_BODY;
	 }

	public Object getProperty() {
		return property;
	}

	public void setProperty(Object property) {
		try {
			// 对EL表达式的支持   <xss:encode property="${变量}"></xss:encode>
			if(property != null)
			this.property = ExpressionEvaluatorManager.evaluate("title", property.toString(), Object.class, this, pageContext);
		} catch (JspException e) {
			System.out.println("过滤js自定义标签类set方法错误!");
			e.printStackTrace();
		}   
	}
}


2、创建tld文件
xss.tld如下
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
     <tlibversion>1.0</tlibversion>
     <jspversion>1.1</jspversion>
     <tag>
        <name>encode</name>
        <tagclass>myTags.JSFilterTag</tagclass>
        <bodycontent>jsp</bodycontent>
        <attribute>
            <name>property</name>
            <rtexprvalue>true</rtexprvalue> 
        </attribute>
     </tag>
</taglib>


3、引入与使用
index.jsp中的应用
<%@ taglib uri="/WEB-INF/xss.tld" prefix="xss" %>
...
<xss:encode property="<ssss>"></xss:encode>

你可能感兴趣的:(jsp,tags)