1.自定义标签类:(注:spring 环境,但由于类用于jsp中,IOC失效)
package org.bavtsp.sys.tag;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;
import org.dppc.bavtsp.sys.entity.Driver;
import org.dppc.bavtsp.sys.service.DriverService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
*
***************************************************************
* @描述 : 驾驶员自定义标签类
* @作者 : gao
* @版本 : v1.0
* @日期 : 2016-5-12
****************************************************************
*/
public class DriverModel extends TagSupport {
Logger logger = Logger.getLogger(DriverModel.class);
public Integer drId; //外部传入的参数
public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
DriverService adminService = getChannelService();
Driver driver = adminService.get(drId.toString());
if(driver!=null&&driver.getName()!=null){
out.print(driver.getName());
}else{
out.print("数据已不存在");
}
} catch (IOException e) {
logger.error("自定义标签获取驾驶员名字失败!");
}
return TagSupport.EVAL_PAGE;
}
public void setDrId(Integer drId) {
this.drId = drId;
}
public DriverService getChannelService() {
ServletContext servletContext = pageContext.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
return wac.getBean(DriverService.class);
}
}
2.标签说明 文件tags.tld,可放于WEB-INF,一个文件可对多个标签类作说明
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "web-
jsptaglibrary_1_2.dtd" >
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.1</jsp-version>
<short-name>show</short-name> <pre name="code" class="html"><span style="white-space:pre"> </span> <tag>
<name>driverName</name>
<tag-class>org.bavtsp.sys.tag.DriverModel</tag-class>
<body-content>empty</body-content>
<attribute>
<name>drId</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue><!-- 允许使用el表达式传值-->
</attribute>
</tag>
<tag> <name>vehicleName</name> <tag-class>org.bavtsp.sys.tag.VehicleModel</tag-class> <body-content>empty</body-content> <attribute> <name>veId</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag></taglib>
3.jsp页面引入自定义标签,前缀自己定义:
<%@ taglib prefix="show" uri="../../tags.tld" %>
4.jsp页面引用
<show:driverName drId="${vehicle.driverID }"/>