目录
- JSTL标签库概述
- if标签
- for标签
- choose、when、otherwise标签
跳转到目录 JSTL标签库 全称是指 JSP Standard Tag Library JSP标准标签库。是一个不断完善的开放源代码的JSP标签库。 EL表达式主要是为了替换jsp中的表达式脚本,而标签库则是为了替换代码脚本。这样使得整个jsp页面变得更佳简洁。
1.导入jstl相关jar包
2.引入标签库:taglib指令引入:
3.使用标签
JSTL由五个不同功能的标签库组成。
功能范围URI前缀核心标签库–重点http://java.sun.com/jsp/jstl/corec国际化标签http://java.sun.com/jsp/jstl/fmtfmt函数http://java.sun.com/jsp/jstl/functionsfn数据库(不使用)http://java.sun.com/jsp/jstl/sqlsqlXML(不使用)http://java.sun.com/jsp/jstl/xmlx 核心标签库 1、if标签跳转到目录
-
作用 <c:if>标签 判断表达式的值,如果表达式的值为 true 则执行其主体内容。
-
属性
@WebServlet("/ifTag")
public class ifServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("num");
request.setAttribute("num", username);
request.getRequestDispatcher("/jstl/if.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
JSTL标签库_if标签
num 为偶数!
num 为奇数!
2、for标签
跳转到目录
-
作用 <c:forEach>起到java代码的for循环作用,可以迭代一个集合中的对象-可以是数组,也可以是list,也可以是map对象。
-
属性
varStatus状态: 作用:指定保存迭代状态的对象的名字,该变量引用的是一个LoopTagStatus类型的对象 通过该对象可以获得一些遍历的状态,如下:
- begin 获取begin属性里的值
- end 获取end属性里的值
- count 获取当前遍历的个数
- index 获取当前索引值
- first 获取是否是第一个元素
- last 获取是否是最后一个元素
- current 获取当前遍历的元素对象
@WebServlet("/forTag")
public class ForServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 自己在url中拼写参数 ?num=28
String num = request.getParameter("num");
request.setAttribute("num", num);
request.getRequestDispatcher("/jstl/for.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
JSTL标签库_for标签
${i}
@WebServlet("/for2Tag")
public class For2Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList al = new ArrayList();
al.add("Tom");
al.add("Lucy");
al.add("Hello");
request.setAttribute("al", al);
ArrayList al2 = new ArrayList();
al2.add(new User("yasu", "123"));
al2.add(new User("dong", "531"));
al2.add(new User("tian", "232"));
request.setAttribute("al2", al2);
request.getRequestDispatcher("/jstl/for2.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
${str}
${vs.index}---${user.name} --- ${user.pwd}
3、choose、when、otherwise标签
跳转到目录
-
作用 标签与Java switch语句的功能一样,用于在众多选项中做出选择。 switch语句中有case,而标签中对应有,switch语句中有default,而标签中有。
-
属性 标签没有属性。 标签只有一个属性。 标签没有属性。
的属性
属性描述是否必要默认值test条件是无
JSTL标签库_choose标签
成绩为A
成绩为B
成绩为C
成绩为E, 不及格!