现在的位置: 首页 > 综合 > 正文

用户自定义的标签属性

2012年11月13日 ⁄ 综合 ⁄ 共 2279字 ⁄ 字号 评论关闭

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
extends TagSupport

{

    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
ServletException

    {

       Properties p = new Properties();

      

       try

       {

           ServletContext context =
config.getServletContext();

          

           InputStream is =
context.getResourceAsStream(
"/WEB-INF/message.properties");

          

           p.load(is);

           is.close();

           //properties放置到application范围内以供其他组件使用。

           context.setAttribute("p",p);

       }

       catch (Exception e)

       {

           // TODO: handle exception

       }

    }

}

 

3.创建自己的标签库

myTag.tld

<?xml version="1.0"
encoding="UTF-8"?>

<!DOCTYPE
taglib

        PUBLIC "-//Sun Microsystems, Inc.//DTD
JSP Tag Library 1.2//EN"

    "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>

      

抱歉!评论已关闭.