EL+JSTL

来源:互联网 发布:知乎 酒吧假酒 编辑:程序博客网 时间:2024/04/27 22:53

EL+JSTL

EL: expression language: 表达式语言

代替<%=%>

目的:便于获取数据,简化JSP

语法:${key} 相当于xxx.getAttribute()

如果通过el找不到该数据则显示””

回顾:

1本页面 pageContext

2 上下文 request

3 浏览器 session

4 服务器 application

共有方法:setAttribute() getAttribute()

 

关于优先级:

pageContext>request>session>application

pageContext.setAttribute("name","jack");

request.setAttribute("name", "amy");

session.setAttribute("name", "li");

application.setAttribute("name", "tom");

 

如果以上四个都有,而我们需要获得其中某一个:

语法: ${xxx.name}

xxx代表:

pageScope

requestScope

sessionScope

applicationScope

 

如果用El显示对象属性 :${对象key.属性}

例子:

Stu s1=new Stu("小明",12);

request.setAttribute("s1", s1);

 <h1>${s1.name}--${s1.age}</h1>

如果通过EL表示集合

request.setAttribute("arr",arr);

<h1>${arr[0]}</h1> --表示第一个

 

通过el判断某个对象是否为null

${empty key如果该key对象为null则返回true ,否则返回false

 

 

EL 获取表单元素的提交

${param.name }

例子:

表单页面 

<form action="a.jsp" method="post">

   <input type="text" name="username" />

   <input type="submit" value="提交"/>

提交的页面

 <h1>${param.username }</h1>

 

EL也能够进行算术运算

特殊${5/2} 除法是求一个精确的值

 

EL 的关系运算符

== != >  >=  <  <= 返回true/false

EL的逻辑运算符

&&  ||  !

 

EL 是来获取和显示数据的,但是如果有逻辑代码(if for..),就需要搭配 JSTL

 

JSTL:java standard tag library :JSP标准标签库 用来代替 <%%>

注释:<%-- xxx --%> 同时也能注释<%%>

 

在使用之前,需要引入标签库

 

 

1 out  相当于 out.print()

语法: <c:out value="" /> 

value可以放EL

:<c:out value="${name}" />

 

2 set 设置变变量值和对象属性(该对象必须是一个javabean)

 

设置普通值

<c:set var=""  value="" scope="page|request|session|application"/>

例子:

<c:set var="xxx"  value="查查查" scope="page"/>

${xxx }

 

设置对象属性

 <jsp:useBean id="s3" class="com.beans.Stu" scope="page" ></jsp:useBean>

<c:set target="${s3}" property="name" value="小天" />

 <c:set target="${s3}" property="age" value="18" />

 ${s3.name }

${s3.age }

补充JSP标签:

转发:<jsp:forward page="a.jsp"></jsp:forward>

 

3 remove

语法:

<c:remove var=""/>

相当于 setAttribute(“”,null)

例子:

<c:set var="name" value="jack" />

   ${empty name }

<c:remove var="name"/>

${empty name }

 

4 if (没有else)

语法:

<c:if test="条件" [var=xxx][scope=””]>写东东</c:if>

注意:一般条件会用到EL

var=xxx 返回true(当条件为真)或者false(当条件为假)

 

 

5 循环

<c:forEach [items="集合"] var="i" [begin="1"  end="10" step="1"]>

   ${i }

   </c:forEach>

var :代表循环中的每一个元素名

begin:起始位置

end:结束位置

step:步长

items:集合 --一般搭配elitems=${arr}

 

 

在一个页面中导入另外一个页面

1 frameset

2 <%@ includ file=”xx.jsp” %>

3 <jsp:include page="xx.jsp" />

4 <c:import url="xx.jsp" />

5 jQuery对象.load(xx.jsp)

 

URL:保存地址+参数,以备用在其他跳转的地方

 <c:url value="a.jsp" var="myurl">

   <c:param name="username" value="abc"/>

   <c:param name="userpwd" value="123"/>

  </c:url>

 

重定向:

<c:redirect url="a.jsp">

   <c:param name="username" value="abc"/>

   <c:param name="userpwd" value="123"/>

 </c:redirect>