`
guiqing85
  • 浏览: 162647 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

JSP学习笔记(五) EL表达式 JSTL

阅读更多
1 EL
Expression Language

1)语法
表达式 VS EL表达式语言 (JSP2.0)
<%= %> <=> ${}
<%=name%> <=> ${name}

2)文字
在 EL 表达式中,数字、字符串、布尔值和 null 都可以被指定为文字值。
字符串可以用单引号或双引号定界。布尔值被指定为 true 和 false 。
例子:
表达式                              值
${100}                             100
${-168.18}                         -168.18
${3.8E18}                          3.8E18
${3.8e-18}                         3.8e-18
${3.14159265}                      3.14159265                 

${"Hello JSP EL!"}                 Hello JSP EL!     等价于 <%="Hello JSP EL!"%>         
${'Hello JSP EL...'}               Hello JSP EL...

${true}//can be TRUE?              true
${false}//can be FALSE?            false

${str==null}                       true
                       
3)EL 运算符
类别          运算符
算术运算符    +、-、*、/(或 div)和 %(或 mod)
关系运算符     ==(或 eq)、!=(或 ne)、<(或 lt)
              >(或 gt)、<=(或 le)和>=(或 ge)
逻辑运算符    &&(或 and)、||(或 or)和 !(或 not)
验证运算符    empty 
empty 判断一个变量是否为null或是否包含有效数据
if(name==null||name.equlas(""))等价于
${empty name}
表达式                              值
${3+5}                              8
${3+5.1}                            8.1
${"Hello"+",narci!"}                error,没有重载

${5*2}                              10

${9.3/3}                            3.1
${9.3 div 3}                        3.1
${8 div 0}                          Infinity

${9%2}                              1
${9 mod 2}  
                       1
   <% String name="";
      request.setAttribute("name",name);
    %>
${empty name}                       true

${8*6>68?"Yes":"No"}                No

4)变量和JavaBean属性数据输出
表达式语言输出变量,是到范围对象(pageContext,request,session,
application)中查找相应属性。而非直接在页面中查找实例或局部变量.

表达式语言查找变量的顺序是:
pageContext -> request -> session->application,
所有范围都未找到时,赋值null

5)存取器
[]    ->输出对象属性值,输出数组或集合中对应索引值
.     ->输出对象属性值

<%
Student stu=new Student();
stu.setName("Alice");
session.setAttribute("stu",stu);
%>

${stu["name"]}   ${stu['name']} ${stu.name}

  List aList = new ArrayList();
  aList.add("China");
  aList.add(88);
  aList.add(168.18);
 
  session.setAttribute("aList", aList);

${aList[0]}
${aList[1]}
${aList[2]}


  Map map = new HashMap();
  map.put("name", "Kitty");
  map.put("age", "25");
  map.put("date", new Date());
  map.put("aList", aList);
  session.setAttribute("map", map);

${map.date}
${map["date"]
${map['date']
${map.aList[0]}
${map["aList"][0]}

6)隐式对象(内建对象)
el提供了自己的一套内建对象,方便在页面内对各种常用数据信息的访问.

pageContext
pageScope
requestScope
sessionScope
applicationScope
param   request.getParameter()
paramValues
header request.getHeader()
headerValues
cookie request.getCookies()
initParam         context param

例子:
用户登录
<input type="text" name="stuName"/>
<input type="password" name="stuSex"/>
<input type="password" name="stuAge"/>
<--提交-->
<jsp:useBean id="stu" scope="session" class="vo.Student"/>
<jsp:setProperty name="name" property="name" value="${param.stuName}"/>
<jsp:setProperty name="sex" property="password" value="${param.stuSex}"/>
<jsp:setProperty name="sex" property="password" value="${param.stuAge}"/> 


<%
  pageContext.setAttribute("name", "page");
  request.setAttribute("name", "request");
  session.setAttribute("name", "session");
  application.setAttribute("name", "application");
%>
${name}  //pageContext -> request -> session->application
${pageScope.name}
${requestScope.name}
${sessionScope.name}
${applicationScope.name}

兴趣 <input type="checkbox" name="habit" value="Reading"/>看书
     <input type="checkbox" name="habit" value="Game"/>玩游戏
     <input type="checkbox" name="habit" value="Travel"/>旅游
     <input type="checkbox" name="habit" value="Music"/>听音乐
     <input type="checkbox" name="habit" value="Tv"/>看电视
    
     //提交
     ${paramValues.habit[0]}"
     ${paramValues.habit[1]}"
     ${paramValues.habit[2]}"
     ${paramValues.habit[3]}"
     ${paramValues.habit[4]}"
web.xml
...
  <context-param>
    <param-name>server</param-name>
    <param-value>Tomcat5.5</param-value>
  </context-param>
...
${initParam.server}

${header["host"]}
${header["accept"]}
${header["user-agent"]}

可以自由设置是否支持表达式语言
<%@page isELIgnored="false"%> : default:false可以使用EL
${name}
配置web.xml也可达到同样的效果(同时存在,那种起作用?)
(禁用脚本和EL)
...
<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-ignored>true</el-ignored>
    <scripting-invalid>true</scripting-invalid>
  </jsp-property-group>
</jsp-config>
....

2 JSTL
JSP Standard Tag Library

1)如何使用JSTL
a、复制jstl的jar包(jstl.jar,standard.jar)到/WEB-INF/lib
b、在使用jstl功能的jsp页面中增加指令
<%@taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
<%@taglib prefix=“x” uri=“http://java.sun.com/jsp/jstl/xml”%>
<%@taglib prefix=“fmt” uri=“http://java.sun.com/jsp/jstl/fmt>
<%@taglib prefix=“sql” uri=“http://java.sun.com/jsp/jstl/sql”%>
<%@taglib prefix=“fn”uri=“http://java.sun.com/jsp/jstl/functions”%>

2)core:
一般用途
在JSTL中,一般用途的标签主要是指具有输出,设置变量,
和错误处理等功能的标签,他们在jsp中使用很频繁,它们有:
a、<c:set>
语法:<c:set value=”value” var=”varName”
      [scope= “{page|request|session|application}”]/ >
     
      <c:set value=”value” target=”target” property=”propertyName”/ >
这个标签用于在某个范围(page,request,session,application)里面设置特定的值
(默认为page),或者设置某个已经存在的javabean的属性。
例子:
<c:set var="counter" value="200"/>
${counter}//输出

<c:set var="china">
the People's Replublic of China
</c:set>
${china}

可以指定范围,默认是page
<c:set value="20" var="maxIdelTime" scope="session"/>
${maxIdelTime}

设置JavaBean的值
<jsp:useBean id="stu" class="vo.Student"/>
<c:set value="Sofei" target="${stu}" property="name"/>
${stu.name}

b、<c:remove>
语法:
<c:remove var=”varName” [scope= “{page|request|session|application}”]/ >
它的作用是删除某个变量或者属性。
例子:
<c:set value="10000" var="maxUser" scope="application"/>
<c:set value="10" var="count" scope="session"/>
<c:set value="10" var="count"/>
${maxUser}
${count}
<c:remove var="maxUser" scope="application"/>
<c:remove var="count" scope="session"/>
${maxUser}
${count}

c、<c:out>
语法:<c:out value=”value” [escapeXml]=”{true|false}”
                        [default=”defaultValue”]/>
注意:escapeXml的作用是是否将代码交给xml解析器解释,
true为交给xml解析器解释,false为交给浏览器解释
例子:
<c:set var="sessionAttr" value="sessionValue" scope="session"/>
<c:set var="pageAttr" value="pageValue" scope="page"/>
<c:set var="requestAttr" value="requestValue" scope="request"/>
<c:out value="以下输出的是前面设置的属性<br>" escapeXml="false"/>

<c:out value="${sessionAttr}"/><br>
<c:out value="${pageAttr}"/><br>
<c:out value="${requestAttr}"/><br>
<c:out value="${nodefined}" default="没有nodefined这个变量"/>

d、<c:catch>
它的作用是捕捉由嵌套在它里面的标签所抛出来的异常。类似于<%try{}catch{}%>
语法:<c:catch [var=”varName”]>nested actions</c:catch>
例子:
<c:catch var="error">
<%
Integer.parseInt("abc");
%>
</c:catch>

<c:out value="${error}"/>
<c:out value="${error.message}"/>
<c:out value="${error.cause}"/>

条件判断
  <c:if test="${param.age<20}">
    <font size="4" color="red">年龄尚小,不能结婚!</font>
  </c:if>
 
  <c:if test="${!empty param.count}">
    <c:choose>
      <c:when test="${param.count>200}">
        <h2>欢迎你,VIP用户</h2>
      </c:when>
      <c:otherwise>
        <h2>感谢关注,继续努力!</h2>
      </c:otherwise>
    </c:choose>
  </c:if>
 
循环
a、 <c:if>
语法:
    <c:if test=”testCondition” var=”varName”
    [scope=“{page|request|session|application}”]>
        Body内容
    </c:if>
例子:
<c:set var="age" value="16"/>
<c:if test="${age<18}">
<h1 align=center>您尚未成年,不能进入游戏中心!</h1>
</c:if>

b、<c:choose>
例子:
<c:set var="tax" value="5000" />
<c:choose>
<c:when test="${tax <=0}">
<hr>您今年没有纳税!
    </c:when>
<c:when test="${tax<=1000&&tax>0}">
<hr>您今年缴纳的税款为${tax},加油!
    </c:when>
<c:when test="${tax<=3000&&tax>1000}">
<hr>您今年缴纳的税款为${tax},再接再励哦!
    </c:when>
<c:otherwise>
<hr>您今年纳税超过了3000元,多谢您为国家的繁荣富强作出了贡献!
    </c:otherwise>
</c:choose>

c、<c:forEach>
语法: <c:forEach [var=”varName”] items=”collection”  [varStatus=”varStatusName”]
       [begin=”begin”] [end=”end”] [step=”step”]>
       Body 内容
       </c:forEach>
例子:
<%
List aList=new ArrayList();
aList.add("I");
aList.add("am");
aList.add("an");
aList.add("excellent");
aList.add("student");
request.setAttribute("aList",aList);
%>
<center>
<table border=1>
<c:forEach var="word" items="${aList}">
<tr><td>${word }</td></tr>
</c:forEach>
</table>
</center>

<c:forEach items='${header}' var='h'>
<ul>
<li>Header name:<c:out value="${h.key}"/>
<li>Header name:<c:out value="${h.value}"/>
</ul>
</c:forEach>
等价于:
<c:forEach items='${headerValues}' var='hv'>
   <ul>
      <li>Header name: <c:out value='${hv.key}'/></li>
      <c:forEach items='${hv.value}' var='value'>
           <li>Header Value: <c:out value='${value}'/></li>
      </c:forEach>
   </ul>
</c:forEach>

另外一种用法:
<c:forEach var="count" begin="10" end="100" step="10">
  <c:out value="${count}"/><br>
</c:forEach>

 
URL
a、<c:import> 相当于<jsp:include>
<c:import url="footer.jsp" charEncoding="GBK">
<c:param name="name" value="Java"/>
</c:import>
b、<c:url>
用于构造URL,主要的用途是URL的重写。
<c:url var="footer1" value="footer.jsp"/>
<c:url var="footer2" value="footer.jsp" scope="page">
    <c:param name="name" value="Sofie"/>
</c:url>
<c:out value="${footer1}"/>
<c:out value="${footer2}"/>

c、<c:redirect>
<c:redirect url="${footer2}"/>

SQL
<sql:setDataSource>
<sql:query>
<sql:update>
<sql:transaction>
<sql:param>
a、查询
<%@page contentType="text/html; charset=GBK"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/tarena" user="narci" password="11" />
<sql:query var="rs" dataSource="${ds}" sql="select * from student" />
//stu.字段名
<c:forEach var="stu" items="${rs.rows}">
<tr>
<td>${stu.student_id}</td>
<td>${stu.student_name}</td>
<td>${stu.student_sex}</td>
<td>${stu.student_age}</td>
<td>${stu.student_desc}</td>
</tr>
</c:forEach>

b、插入记录
  <sql:update dataSource="${ds}"
  sql="insert into student values(108,'Tany','m',32,'***')" var="i">
  </sql:update>
  <hr>插入${i}条记录.

c、更新记录

  <sql:update dataSource="${ds}"
  sql="UPDATE student SET student_name='TingTing' WHERE student_id=108" var="i">
  </sql:update>
  <hr>更新${i}条记录.

  ${i}条记录写入

<sql:param>
作用:设置sql语句中“?”表示的占位符号的值。
  <sql:update dataSource="${ds}"
sql="UPDATE student SET student_name=? WHERE student_id=?" var="i">
<sql:param value="Killer" />
<sql:param value="108" />
  </sql:update>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics