jsp自定义标签

来源:互联网 发布:夏茗悠扒皮知乎 编辑:程序博客网 时间:2024/06/05 10:16

一:编写类

package cn.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;

@SuppressWarnings("serial")
public class ViewIpTag extends TagSupport{

public int doEndTag() throws JspException{

JspWriter out=this.pageContext.getOut();
HttpServletRequest request=(HttpServletRequest) this.pageContext.getRequest();

String ip=request.getLocalAddr();
try {
out.print(ip);
} catch (IOException e) {
throw new RuntimeException(e);
}
return super.doStartTag();
}


}


二:文件(注意:此文件应该放在WEB-INF目录下)

package cn.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;


@SuppressWarnings("serial")
public class ViewIpTag extends TagSupport{

public int doEndTag() throws JspException{

JspWriter out=this.pageContext.getOut();
HttpServletRequest request=(HttpServletRequest) this.pageContext.getRequest();

String ip=request.getLocalAddr();
try {
out.print(ip);
} catch (IOException e) {
throw new RuntimeException(e);
}
return super.doStartTag();
}


}

三:编写jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://www.clyao.cn" prefix="clyao" %>
<%
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 'tag.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">


  </head>
  
  <body>
您德 ip是:<clyao:viewIP/>
  </body>
</html>

四:到此,恭喜您已经配好一个自定义标签。。。。