sun公司提供的jstl虽然比较强大,但是开发中很难满足我们所有的需求,并且开发也禁止在jsp中写很多java代码,因此很多场景需要自己定义标签进行项目开发
sun提供的标签库引用方式:<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
以下案例为自定义标签开发
自定义标签开发流程:
1.需要标签处理器类,用来替换jsp中的Java代码,也就是我们的功能代码类
2.标签处理器类需要描述到一个tld的文件中( tld直接放在WEB-INF下即可)
3.jsp应用 <%@taglib uri="xxx" prefix="xxx"%>
注意: prefix尽量和描述的tld文件名一致,便于开发查找
标签处理器类
public class Escape extends SimpleTagSupport{ public void doTag() throws JspException, IOException { JspFragment js=this.getJspBody(); StringWriter sw=new StringWriter(); js.invoke(sw); String content=sw.getBuffer().toString(); content=filter(content); this.getJspContext().getOut().write(content); } private String filter(String message) { if(message==null){ return null; } char content[]=new char[message.length()]; message.getChars(0,message.length(),content,0); StringBuffer result=new StringBuffer(content.length+50); for(int i=0;i<content.length;i++){ switch (content[i]) { case ‘<‘: result.append("<"); break; case ‘>‘: result.append(">"); break; case ‘&‘: result.append("&"); break; case ‘"‘: result.append("""); break; default: result.append(content[i]); } } return result.toString(); } }
simple.tld
<?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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>JSTL 1.1 core library</description> <tlib-version>1.0</tlib-version> <short-name>simple</short-name> <uri>http://simple.tag</uri> <tag> <name>escape</name> <tag-class>tag.Escape</tag-class> <body-content>scriptless</body-content> </tag> </taglib>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://simple.tag" prefix="simple" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>转义标签</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <simple:escape> <a href="http://www.baidu.com">百度</a> </simple:escape> <a href="http://www.baidu.com">百度</a> </body> </html>
启动tomcat访问结果展示,通过自定义标签做到了特殊字符的转义