这些可重用的标签能处理复杂的逻辑运算和事务,或者定义JSP网页的输出内容和格式。
2 创建JSP标签的步骤
•(1)创建标签的处理类(继承TagSupport类)
•(2)创建标签库描述文件 (tld文件) 与web.xml放在相同的目录下面
•(3)在JSP文件中引入标签库,然后插入标签,例如:<mm:hello/>
3 示例1
Step1 创建标签处理类
继承TagSupport类,重写doStartTag和doEndTag方法
@Override public int doStartTag() throws JspException { try { pageContext.getOut().print("i miss you bingjia <br>"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return TagSupport.EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { try { pageContext.getOut().print("that is true~!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return TagSupport.EVAL_PAGE; }
主要标签为tag中的name tag-class
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>myTag</short-name> <uri>/myTag</uri> <tag> <name>firstTag</name> <tag-class>com.songxu.tag.MyTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
<%@ taglib uri="/myTag" prefix="myTag" %>
uri 与step2中的uri一致,prefix类似于命名空间,防止不同标签库的同名标签
<body> <myTag:firstTag/> </body>
(1)新建servlet,在web服务器启动时启动,并把properties加载到application对象中
在web.xml设置servlet的load-on-startup标签
<load-on-startup>10</load-on-startup>实现init方法
public void init(ServletConfig config) throws ServletException { Properties ps = new Properties(); try { ServletContext context = config.getServletContext(); InputStream is = context .getResourceAsStream("/WEB-INF/my.properties"); ps.load(is); is.close(); // 将properties对象放置到application范围内供其他组件使用 context.setAttribute("ps", ps); } catch (Exception ex) { ex.printStackTrace(); } }(2) 编写tag 获取property 并显示。必须定义变量key,并编写set,get方法。否则无法获得标签的属性
String key; public String getKey() { return key; } public void setKey(String keyString) { this.key = keyString; } @Override public int doEndTag() throws JspException { Properties properties=(Properties) pageContext.getAttribute("ps", pageContext.APPLICATION_SCOPE ); String messegString=properties.getProperty(key); try { pageContext.getOut().println("key"+key+" value:"+messegString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return EVAL_PAGE; }
<tag> <name>message</name> <tag-class>com.songxu.tag.MyTag2</tag-class> <attribute> <name>key</name> <required>true</required> </attribute> </tag>
<myTag:message key="miss"/>