自定义标签可以大大方便我们的页面控件编写,并且可以实现很多统一的管理。
首先需要引入支持自定义标签的jar包,有两种方式,
可以直接在maven里面引入依赖:
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
二可用tomcat的自带的jsp-api
一般在WEB-INF目录下创建一个tags文件夹 创建的自定义标签文件以tag结尾
在jsp页面引入自定义标签
<!-- 引入自定义标签 -->
<%@taglib tagdir="/WEB-INF/tags" prefix="ex" %>
案例
1、自定义标签实现两数相加
<%@tag pageEncoding="UTF-8" %>
<!-- 定义属性的标签 name:属性名 type:属性类型 required:是否是必填项(true表示必填 false表示可选项)-->
<%@attribute name="p1" type="java.lang.Double" %>
<%@attribute name="p2" type="java.lang.Double" %>
<%
double result=p1+p2;
%>
<%=result%>
jsp的使用
<!-- 自定义标签 -->
<ex:add p1="23" p2="23"></ex:add>
2、自定义标签实现if
<jsp:doBody></jsp:doBody>输出引用此标签jsp页面的所有内容
<%@tag pageEncoding="UTF-8"%>
<%@attribute name="test" required="true" type="java.lang.Boolean"%>
<%
if(test){
%>
<jsp:doBody></jsp:doBody>
<%
}
%>
jsp中的使用
<ex:if test="${1==1 }">mmm</ex:if>
3、自定义标签实现普通for循环
<%@tag pageEncoding="UTF-8" %>
<%@attribute name="var" type="java.lang.String" %>
<%@attribute name="begin" type="java.lang.Integer" %>
<%@attribute name="end" type="java.lang.Integer" %>
<%@attribute name="step" type="java.lang.Integer" %>
<%
for(int i=begin;i<=end;){
request.setAttribute(var, i);
%>
<jsp:doBody></jsp:doBody>
<%
i=i+step;
}
%>
jsp中的使用<!-- 自定义普通for循环 -->
<ex:for var="i" begin="1" end="10" step="1">
${requestScope.i}
</ex:for>
3、
自定义标签实现foEach循环
<!-- 引入jdk中的包 -->
<%@tag import="java.util.Collection"%>
<%@tag pageEncoding="UTF-8" %>
<%@attribute name="var" type="java.lang.String" required="true" %>
<%@attribute name="items" type="java.lang.Object" %>
<%
//判断是否是集合
out.println(items.getClass().getName());
if(items instanceof Collection){
Collection<String> c=(Collection)items;
for(String ctemp:c){
request.setAttribute(var, ctemp);
%>
<jsp:doBody></jsp:doBody>
<%
}
}
//判断是否是数组
if(items.getClass().getName().startsWith("[")){
String[] c=(String[])items;
for(String ctemp:c){
request.setAttribute(var, ctemp);
%>
<jsp:doBody></jsp:doBody>
<%
}
}
%>
在jsp中的使用
<!-- 自定义foEach循环 -->
<!-- 集合 -->
<ex:foEach var="my" items="${pageScope.myList }">
${requestScope.my }
</ex:foEach>
<!-- 数组 -->
<ex:foEach var="my" items="${fn:split('a,b,c',',') }">
${requestScope.my }
</ex:foEach>