java? Custom tag, my first custom tag!

Custom tag, my first custom tag!

 

Two steps in total

  1. Write a java class to implement the tag interface, and move the java code in the jsp page to this class (label processor class)
  2. Write a tag library descriptor (tld) file, in which the tag handler class is described as a tag

I. Case Study.

Output client IP

 

   ViewIP.jsp 

   
<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib uri="/WEB-INF/firstTag.tld" prefix="itcast"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

 

         <h4>Your iP:</h4>

         <itcast:viewIP/>

</body>

</html>
ViewIP.jsp

 

 

Create a tld file in the WEB-INF directory

  firstTag.tld

  
<?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">

    <description>A tag library exercising SimpleTag handlers.</description>

    <tlib-version>1.0</tlib-version>

    <short-name>view</short-name>

    <uri>/WEB-INF/firstTag.tld</uri>

    <tag>

        <name>viewIP</name>

        <tag-class>Tag.viewIPTag</tag-class>

        <body-content>empty</body-content>

    </tag>

   </taglib>
firstTag.tld

 

 

Write the label processor class:

  viewIPTag.java

  
package 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{

        

         public int doStartTag() throws JspException{

                   HttpServletRequest request=(HttpServletRequest) this.pageContext.getRequest();

                  

                   JspWriter out=this.pageContext.getOut();

                  

                   String ip=request.getRemoteAddr();

                  

                   try {

                            out.print(ip);

                   } catch (IOException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                   return super.doStartTag();

         }

}
viewIPTag.java

 

Effect screenshot:

  

Tags: Java JSP xml encoding

Posted on Tue, 31 Mar 2020 16:16:28 -0700 by ken72