自定义标签使用
程序员文章站
2022-03-04 11:51:44
...
在jsp页面使用此自定义标签
1 创建自定义标签类
public class UserInfoTag extends TagSupport {
private UserInfo user;
@Override
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse)pageContext.getResponse();
HttpSession session = request.getSession();
try {
JspWriter out = this.pageContext.getOut();
if(user == null) {
out.println("No UserInfo Found...");
return SKIP_BODY;
}
out.println("<table width='500px' border='1' align='center'>");
out.println("<tr>");
out.println("<td width='20%'>Username:</td>");
out.println("<td>" + user.getUserName() + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Age:</td>");
out.println("<td>" + user.getAge() + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Email:</td>");
out.println("<td>" + user.getEmail() + "</td>");
out.println("</tr>");
out.println("</table>");
} catch(Exception e) {
throw new JspException(e.getMessage());
}
return SKIP_BODY;
}
//getter and setters
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
}
2 在Web-Inf创建标签库描述文件.tdl(Tag Library Description)
<?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>showUserInfo</name> <!—指定标签类文件的全路径 --> <tag-class>com.mytags.UserInfoTag</tag-class> <!--如果不需要标签体则设置empty,反之设定jsp --> <body-content>empty</body-content> <!—设定属性(如果有的话) --> <attribute> <!—指定标签名 --> <name>user</name> <!—是否是必须,如果非必须没设置则为空 --> <required>false</required> <!—是否可在属性中使用表达式 --> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3 配置web.xml
<jsp-config> <taglib> <taglib-uri>/mytaglib</taglib-uri> <taglib-location>/WEB-INF/mytaglib.tld</taglib-location> </taglib> </jsp-config>
4 页面中使用
<%@ taglib uri="/mytaglib" prefix="cc"%>
<%
UserInfo user = new UserInfo();
user.setUserName("Xuwei");
user.setAge(33);
user.setEmail("[email protected]");
pageContext.setAttribute("userinfo", user);
%>
<cc:showUserInfo user="${pageScope.userinfo }" />
上一篇: vue+elementui table表格点击单元格单元格改变背景色
下一篇: 自定义标签使用