作用
在我们开发中,界面和程序代码是分开做的美工做界面但是美工不懂得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; } }
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展示后
结果正确
原文地址:http://blog.csdn.net/h348592532/article/details/45980215