作用
在我們開發中,界面和程式代碼是分開做的美工做界面但是美工不懂得Java語言如果我們把Java代碼寫在jsp檔案中,會影響美工工作如果我們使用自定義标簽,到時再jsp中我們隻需要加入一段引用标簽代碼就好了不會影響美工工作此外jsp檔案簡單,友善我們以後修改
1建立類
package com.eyugame.common.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import com.eyugame.common.service.hibernate.HibernateBaseService;
import com.eyugame.security.entity.SysUser;
public class MyTag extends TagSupport {
private static HibernateBaseService hibernateBaseService;
private String username;
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public int doStartTag() throws JspException {
JspWriter writer = this.pageContext.getOut();
/*擷取bean*/
if(hibernateBaseService==null){
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
hibernateBaseService = (HibernateBaseService) webApplicationContext.getBean("hibernateBaseService");
}
/*查詢資料庫*/
SysUser user = hibernateBaseService.findUniqueByHql(SysUser.class, "from SysUser as u where u.username='" + username + "'");
try {
writer.print(user.getNickname());
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspException {
return super.doEndTag();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
建立tld檔案
my.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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 web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>cc</short-name>
<uri>/mytaglib</uri>
<tag>
<name>myTag</name>
<tag-class>com.eyugame.common.tag.MyTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>username</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3.web.xml加入以下配置
<jsp-config>
<taglib>
<taglib-uri>/tagTest </taglib-uri>
<taglib-location>/tld/my.tld</taglib-location>
</taglib>
</jsp-config>
4.jsp頁面加入以下内容
<!--jsp頂部加入, uri是在web項目的上下文路徑 -->
<%@taglib prefix="cc" uri="/tld/my.tld" %>
<!-- 在body内加入 -->
<cc:myTag username="admin" />
先看我資料庫有條記錄
jsp展示後
結果正确