自定义标签库读取文件

jsp

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>

<%@tagliburi="http://www.cgmcc.com/jsp/readfile"prefix="my3"%>

<%

Stringpath=request.getContextPath();

StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">

<html>

<head>

<basehref="<%=basePath%>">

<title>MyJSP'tagreadfile.jsp'startingpage</title>

<metahttp-equiv="pragma"content="no-cache">

<metahttp-equiv="cache-control"content="no-cache">

<metahttp-equiv="expires"content="0">

<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

<metahttp-equiv="description"content="Thisismypage">

<!--

<linkrel="stylesheet"type="text/css"href="styles.css">

-->

</head>

<body>

<my3:readFilefile="/WEB-INF/tld/readfile.tld"/>

</body>

</html>

java

packagecom.cgm.readFile;

importjava.io.IOException;

importjava.io.InputStream;

importjava.util.Scanner;

importjavax.servlet.jsp.JspContext;

importjavax.servlet.jsp.JspException;

importjavax.servlet.jsp.PageContext;

importjavax.servlet.jsp.tagext.JspFragment;

importjavax.servlet.jsp.tagext.JspTag;

importjavax.servlet.jsp.tagext.SimpleTag;

publicclassTagReadFileimplementsSimpleTag{

privateStringfile;

privatePageContextpageContext;

publicStringgetFile(){

returnfile;

}

publicvoidsetFile(Stringfile){

this.file=file;

}

publicvoiddoTag()throwsJspException,IOException{//可以动态生成jsp啊..

//处理逻辑

//开始读文件.

System.out.println("-----------------"+file);

InputStreamin=pageContext.getServletContext().getResourceAsStream(file);

Scannerscanner=newScanner(in,"UTF-8");

while(scanner.hasNext()){

Stringline=scanner.nextLine();

line=line.replace("<","&lt");

line=line.replace(">","&gt");

pageContext.getOut().print(line);

pageContext.getOut().println("</br>");//换行

}

}

publicJspTaggetParent(){

//TODOAuto-generatedmethodstub

returnnull;

}

publicvoidsetJspBody(JspFragmentjspBody){

}

publicvoidsetJspContext(JspContextpc){

this.pageContext=(PageContext)pc;

}

publicvoidsetParent(JspTagparent){

}

}

tld

<?xmlversion="1.0"encoding="UTF-8"?>

<taglibxmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"

version="2.0">

<tlib-version>1.3</tlib-version>

<short-name>my3</short-name>

<uri>http://www.cgmcc.com/jsp/readfile</uri>

<tag>

<name>readFile</name>

<tag-class>com.cgm.readFile.TagReadFile</tag-class>

<body-content>empty</body-content>

<attribute>

<name>file</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

<type>java.lang.String</type>

</attribute>

</tag>

</taglib>

jsp

相关推荐