为了增加jsp代码的可读性尽量需要把页面html代码与java代码分开,所以了解了一下自定义标签的问题。
在WEB-INF下面创建tld文件夹
项目结构
步骤:
- 实现标签处理类;
- 编译tld文件
- 在jsp页面中导入标签库。
package com.winston.tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; /** * @Description:自定义标签1 * @Author Winston * @Version 1.0 2017/4/12 22:18 */ public class CustomTag1 extends SimpleTagSupport { @Override public void doTag() throws JspException, IOException { this.getJspContext().getOut().print("Hello Jsp"); } }
<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <description>customTag</description> <display-name>customTag</display-name> <tlib-version>1.0</tlib-version> <short-name>ct</short-name> <uri>/customTag</uri> <tag> <name>customTag1</name> <tag-class>com.winston.tag.CustomTag1</tag-class> <body-content>empty</body-content> <description>my custom tag1</description> </tag> </taglib>
创建jsp页面
<%-- Created by IntelliJ IDEA. User: Winston Date: 2017/4/12 Time: 22:26 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="ct" uri="/WEB-INF/tld/customTag.tld" %> <html> <head> <title>Title</title> </head> <body> <ct:customTag1/> </body> </html>
执行效果