从文件读取并显示
1.首先定义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>MyTag 1.0 core library</description>
<display-name>MyTag core</display-name>
<tlib-version>1.0</tlib-version>
<!--建议在JSP页面使用的标签前缀-->
<short-name>skye</short-name>
<!--作为tld文件的id,用来唯一标识当前的tld文件,多个tld文件的uri不能重复,通过JSP页面的taglib标签的uri属性来引用-->
<uri>http://skye/jsp/jstl/core</uri>
<!--描述自定义的HelloSimpleTag标签-->
<tag>
<!--标签的名字,在JSP页面上使用标签时的名字-->
<name>readFile</name>
<!--标签所在的全类名-->
<tag-class>tagTest.ReadFileTest</tag-class>
<!--标签体的类型-->
<body-content>empty</body-content>
<!--描述当前标签的属性-->
<attribute>
<!--属性名-->
<name>src</name>
<!--该属性是否为必须-->
<required>true</required>
<!--rtexprvalue run time expression value 当前属性是否可以接受运行时表达式的动态值-->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
2.extends SimpleTagSupport
package tagTest;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.*;
import java.util.regex.Pattern;
public class ReadFileTest extends SimpleTagSupport {
//相对于当前WEB应用的根路径的文件名
private String src;
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public ReadFileTest() {
super();
}
@Override
public void doTag() throws JspException, IOException {
PageContext pageContext = (PageContext)getJspContext();
InputStream in = pageContext.getServletContext().getResourceAsStream(src);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String str = null;
while((str = reader.readLine()) != null){
//正则表达式
str = Pattern.compile("<").matcher(str).replaceAll("<");
str = Pattern.compile(">").matcher(str).replaceAll("&rt");
//str = new String(str.getBytes("ISO-8859-1"),"UTF-8");
pageContext.getOut().println(str);
pageContext.getOut().println("<br>");
}
}
@Override
public void setJspContext(JspContext pc) {
super.setJspContext(pc);
}
}
3.在jsp页面上调用
<%--
Created by IntelliJ IDEA.
User: Skye
Date: 2017/12/13
Time: 14:21
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://skye/jsp/jstl/core" prefix="skye" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
<title>Title</title>
</head>
<body>
<skye:readFile src="/WEB-INF/node.txt"/>
</body>
</html>