zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Apache Struts 2.3.12 GA?
    emacs配置《转》
    vim配置
    vim插件
    git使用
    ubuntu常用设置
    Eclipse如何关联已经clone的Git项目
    变量名、对象引用(指针)与堆栈
    Web项目转换为groovy项目的步骤
    日志 20071208(SvcUtil.exe,高并发网站架构)
  • 原文地址:https://www.cnblogs.com/zhuawang/p/3418682.html
Copyright © 2011-2022 走看看