posts - 51, comments - 17, trackbacks - 0, articles - 9
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

第一个自定义标签的实现

Posted on 2007-06-26 20:04 chenweicai 阅读(288) 评论(0)  编辑  收藏

步一:定义标签

步二:创建标签库描述器TLD diagnostics.tld, 将它放在WEB-INF目录下的tlds文件夹下,diagnostics.tld如下:

<?xml version="1.0"?>
<taglib>
 <tlibversion>1.0</tlibversion>
 <jspversion>1.1</jspversion>
 <shortname>diag</shortname>
 <tag>
   <name>getWebServer</name>
   <tagclass>servlet.GetWebServerTag</tagclass>
   <bodycontent>empty</bodycontent>
 </tag>
</taglib>

步三:编写标签处理器 GetServerTag.java

package servlet;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class GetWebServerTag extends TagSupport {

 @Override
 public int doStartTag() throws JspException {
  try{
   // get the request object from the page context
   HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
   
   // Request information form the web server
   URL url = new URL("http", request.getServerName(), request.getServerPort(), "/");
   URLConnection con = url.openConnection();
   ((HttpURLConnection)con).setRequestMethod("OPTIONS");
   String webserver = con.getHeaderField("server");
   
   // write it to the output stream
   JspWriter out = pageContext.getOut();
   out.print(webserver);
  }catch (IOException e)
  {
   throw new JspException(e.getMessage());
  }
  
  return SKIP_BODY;
 }
 
}


步四: 编写WEB.xml文件

加入:
<jsp-config>
<taglib>
<taglib-uri>diagnostics</taglib-uri>
<taglib-location>/WEB-INF/tlds/diagnostics.tld</taglib-location>
</taglib>
</jsp-config>

步五:编写jsp页面,将标签并入该JSP页面

<%@ taglib prefix="diag" uri="diagnostics"%>
   
<html>
<head>
<title>Basci Example of a Custom Tag</title>
</head>
<body>
<H3>Basci Example of a Custom Tag</H3>
 The web server is <diag:getWebServer/>
</body>
</html>


OK  , so much so this ,


wish you success

<注: 注意红色的地方要一致哦>


只有注册用户登录后才能发表评论。


网站导航: