您也可以創建自定義標籤來完成此操作。這裏是一個裸露的骨頭例如:
創建一個新的TLD文件: WEB-INF/user.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name></short-name>
<tag>
<name>user</name>
<tag-class>tags.UserRoleTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>roles</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
創建自定義標籤種類: 標籤/ UserRoleTag.java
package tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
@SuppressWarnings("serial")
public class UserRoleTag extends TagSupport {
private String roles;
public int doStartTag() throws JspException {
String userRole = (String)pageContext.getAttribute("currentUserRole");
return roles.contains(userRole) ? EVAL_BODY_AGAIN : SKIP_BODY;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
}
創建您的jsp:warfolder/home.jsp
<%@ taglib uri="/WEB-INF/user.tld" prefix="u" %>
<% pageContext.setAttribute("currentUserRole", "admin"); // this value would come from the controller... %>
<u:user roles="admin registered">
welcome admin!
</u:user>
<u:user roles="guest">
welcome guest!
</u:user>
羚牛g這種方法可以讓您的模型和標籤鬆散耦合,並且很可能可以在其他項目中重複使用。