1.创建MyTag类,并继承TagSupport类
增加key属性,并实现doEndTag方法
MyTag.java
import java.util.Properties;
import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport;
public class MyTag { private String key;
public String getKey() { return key; }
public void setKey(String key) { this.key = key; }
@Override public int doEndTag() throws JspException { try { Properties p = (Properties)this.pageContext.getAttribute("p",PageContext.APPLICATION_SCOPE);
String message = p.getProperty(key);
this.pageContext.getOut().println(message);
} catch (Exception e) { e.printStackTrace(); }
return EVAL_PAGE; } }
|
2.创建一个initServlet,把properties中的属性添加到Application范围中
把initServlet设为服务器启动即加载
Message.properties
title=hello world body=welcome |
Web.xml
<servlet> <servlet-name>InitServlet</servlet-name> <servlet-class>com.anllin.servlet.InitServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> |
InitServlet.java
import java.io.InputStream; import java.util.Properties;
import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;
public class InitServlet extends HttpServlet { @Override public void init(ServletConfig config) throws { Properties p = new Properties();
try { ServletContext context =
InputStream is =
p.load(is); is.close(); //把properties放置到application范围内以供其他组件使用。 context.setAttribute("p",p); } catch (Exception e) { // TODO: handle exception } } } |
3.创建自己的标签库
myTag.tld
<?xml version="1.0" <!DOCTYPE PUBLIC "-//Sun Microsystems, Inc.//DTD "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.1</jsp-version> <short-name>myTag</short-name> <uri>/myTag</uri> <display-name>myTag</display-name> <tag> <name>firstTag</name> <tag-class>com.anllin.taglib.MyTag</tag-class>
|