jsp自定义获取contextPath标签

1 标签处理类

package com.project.common.web.taglib.toolkit;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * 输出ContextPath。
 * 
 * @since 2010-2-2 
 * @author chenyu
 * @version 1.00 
 */
public class ContextTag extends TagSupport {
	/**
	 * 输出ContextPath。
	 */
	public int doEndTag() {
		try {
			HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
			//输出contextPath
			pageContext.getOut().print(request.getContextPath());
		} catch (IOException ignored) { }
		return EVAL_PAGE;
	}
	
}

 2 配置类

   web-inf/taglib/tk.tld

   tk.tld如下:

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.0</jspversion>
<shortname>tk</shortname>
<uri>/WEB-INF/taglib/tk.tld</uri>

<tag>
	<name>context</name>
	<tagclass>com.project.common.web.taglib.toolkit.ContextTag</tagclass>
	<bodycontent>empty</bodycontent>
</tag>

</taglib>
 

3 jsp页面调用

 

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib uri="/WEB-INF/taglib/tk.tld" prefix="tk"%>
<!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=GB18030">
<script type='text/javascript' src='<tk:context/>/test.js'></script>
<title></title>
</head>
<body>

</body>
</html>

 4 效果:

  <tk:context/>被替换 获取了web应用的context路径

 

<script type ='text/javascript' src ='/toolkit/test.js' > </script >

你可能感兴趣的:(JavaScript,html,jsp,Web,servlet)