上期给大家介绍了一下EL与JSTL,这期就来继续给大家详细介绍一下EL与JSTL的使用。
目录
一,知识回顾 EL与JSTL的概念:
EL(Expression Language)表达式:
功能:替代jsp页面中的复杂代码
语法:${EL expression}
${bean.name}EL中的隐含对象(pageScope、requestScope、sessionScope、applicationScope
EL运算符(算术 关系 Empty运算符【判断集合中值是否为空 返回true或者false
JSTL:
通用标签:set out remove
条件标签:if
迭代标签:forEach
功能:用来替代jsp中的java代码,从而降低其耦合性
二,使用方式:
JSTL的基本标签:
其中比较常用的就是if和forEach,可以重点记忆。
- 通用标签:set、out、remove
- 条件标签:if
- 迭代标签:forEach
使用步骤:
导入jar包:(jstl的jar包和standard)
将jar包BuildPath(添加牛奶瓶)
在代码上方加上导入语句
<%--tag标签,lib库,导入一个标签库 后面的uri注意不要导入错误--%>
<%@taglib prefix="a" uri="http://java.sun.com/jsp/jstl/core"%>
在进行上方的一系列操作过后,就可以进行JSTL的使用了。
具体使用:
if判断的使用:
//这里可以由用户传进来一个userName
<c:if test="${userName!=null}">
<h1>登录成功</h1>
</c:if>
<c:if test="${userName==null}">
<h1>登陆失败</h1>
<button>请进行登录</button>
</c:if>
forEach循环的使用:
//forEach遍历的是集合,这里的items就是集合的名字,用${}就代表从域里面取出这个集合,var就是给集合里面的元素取了一个名字。
<c:forEach items="${user}" var="u">
<tr>
<th>${u.usersId}</th>
<th>${u.userName}</th>
<th>${u.userpwd}</th>
</tr>
</c:forEach>
EL的基本使用
设置值:
application/session/request/pageContext.setAttribute("对象名","存入的数据")
取值:
${对象名.需要获得的对象属性}
代码示例:
这里是从login.jsp界面接收用户传入的名字和密码,然后存入session中,再跳转到其他页面。
//接收到输入的用户名和密码
String scottName=request.getParameter("scottName");
String scottPassword=request.getParameter("scottPassword");
IScottBiz scottBiz=new ScottBizImpl();
Scott scott=scottBiz.login(new Scott(0,scottName,scottPassword));
if(scott==null){
response.sendRedirect("login.jsp");
}
else{
//首页需要登录数据,将数据存储到session里面去
session.setAttribute("scott", scott);
response.sendRedirect("doIndex.jsp");
}