自定義JSP標籤

1 寫一個標籤處理類
//標籤處理類
public class IpTag implements SimpleTag {
 private PageContext pageContext;
 //Web容器調用NO1
 public void setJspContext(JspContext pc) {
  System.out.println("setJspContext()");
  pageContext = (PageContext) pc;
 }
 //Web容器調用NO2
 public void doTag() throws JspException, IOException {
  System.out.println("doTag()");
  //取得HttpServletRequest請求對象
  HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
  //取得客戶端的IP地址
  String ip = request.getRemoteAddr();
  //取得out(JspWriter)對象
  JspWriter out = pageContext.getOut();
  //向瀏覽器輸出
  out.write("<font size='44' color='red'>"+ip+"</font>");
 }
        ...
}html

2 在/WEB-INF/目錄下,寫一個*.tld文件,目的是讓Web容器知道自定義標籤和標籤處理類的對應關係
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
  <tlib-version>1.0</tlib-version>
  <short-name>simple</short-name>
  <uri>http://java.sun.com/jsp/jstl/simple</uri>
  <tag>
    <name>ip</name>
    <tag-class>cn.itcast.web.jsp.tag.IpTag</tag-class>
    <body-content>empty</body-content>
  </tag>
</taglib>java

3 在JSP頁面中,經過<%@taglib%>指令引用標籤庫
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/simple" prefix="simple" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
   客戶端IP爲:<simple:ip/>
  </body>
</html>web

4 部署web應用,訪問simple.jsp便可瀏覽器

相關文章
相關標籤/搜索