jsp自定义标签1

1.编写一个实现tag接口的java类

package cn.itcast.web.tag;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class ViewIPTag extends TagSupport {

    @Override
    public int doStartTag() throws JspException {
        HttpServletRequest request=(HttpServletRequest) pageContext.getRequest();
        JspWriter out=pageContext.getOut();
        String ip=request.getRemoteAddr();
        try {
            out.print(ip);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return super.doStartTag();
    }    
}

 

2.在tld文件中对标签处理器类进行描述(tld文件的位置必须放在WEB-INF文件夹下)

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
      version="2.1">
  <tlib-version>1.0</tlib-version>
  <short-name>itcast</short-name>
  <uri>http://www.itcast.com</uri>

  <tag>
    <name>viewIP</name>
    <tag-class>cn.itcast.web.tag.ViewIPTag</tag-class>
    <body-content>empty</body-content>
  </tag>

</taglib>

3.在jsp页面中导入和使用自定义标签

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.com" prefix="itcast" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP '1.jsp' starting page</title>
  </head>
  
  <body>
     <!-- 自定义标签输出IP -->
     <itcast:viewIP/>
  </body>
</html>

 

 

 

你可能感兴趣的:(jsp自定义标签)