jsp默认使用的表达式语言:EL表达式,可以直接使用;
struts2的默认表达式语言:OGNL; 简称 s标签
spring中默认的表达式语言:SpEL; 注:spring 3.0 中新增 , spring 3.0之前使用jstl
Apach开源jstl标签库:简称 c标签
1.OGNL的好处以及特点:
Struts 2支持以下几种表达式语言:
- OGNL(Object-Graph Navigation Language),可以方便地操作对象属性的开源表达式语言;
- JSTL(JSP Standard Tag Library),JSP 2.0集成的标准的表达式语言;
- Groovy,基于Java平台的动态语言,它具有时下比较流行的动态语言(如Python、Ruby和Smarttalk等)的一些起特性;
- Velocity,严格来说不是表达式语言,它是一种基于Java的模板匹配引擎,具说其性能要比JSP好。
Struts 2默认的表达式语言是OGNL,原因是它相对其它表达式语言具有下面几大优势:
- 支持对象方法调用,如xxx.doSomeSpecial();
- 支持类静态的方法调用和值访问,表达式的格式为@[类全名(包括包路径)]@[方法名 | 值名],例如:@java.lang.String@format('foo %s', 'bar')或@tutorial.MyConstant@APP_NAME;
- 支持赋值操作和表达式串联,如price=100, discount=0.8, calculatePrice(),这个表达式会返回80;
- 访问OGNL上下文(OGNL context)和ActionContext;
- 操作集合对象。
OGNL的用法
OGNL是通常要结合Struts 2的标志一起使用,如<s:property value="xx" />等。大家经常遇到的问题是#、%和$这三个符号的使用。下面我想通过例子讲述这个问题:
首先新建名为Struts2_OGNL的Web工程,配置开发环境。之前很多朋友在使用Struts 2的过程中都遇到乱码问题。当然乱码问题由来已久,而且涉及多方面的知识,所以并非三言两语可以说明白,而且互联网上也已经有很多这方便的文章,大家可以Google一下。不过,如果你在开发的过程,多注意一下,避免乱码问题也不难。乱码多数是由于编码与解码所使用的方式不同造成的,所以我建议大家将编码方式都设为“utf-8”,如<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>。另外,在配置web.xml时使用ActionContextCleanUp过滤器(Filter),如下面代码所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app id="WebApp_9" version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <display-name>Struts 2 OGNL</display-name>
- <filter>
- <filter-name>struts-cleanup</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ActionContextCleanUp
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts-cleanup</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- </welcome-file-list>
- </web-app>
“#”主要有三种用途:
- 访问OGNL上下文和Action上下文,#相当于ActionContext.getContext();下表有几个ActionContext中有用的属性:
名称 作用 例子 parameters 包含当前HTTP请求参数的Map #parameters.id[0]作用相当于request.getParameter("id") request 包含当前HttpServletRequest的属性(attribute)的Map #request.userName相当于request.getAttribute("userName") session 包含当前HttpSession的属性(attribute)的Map #session.userName相当于session.getAttribute("userName") application 包含当前应用的ServletContext的属性(attribute)的Map #application.userName相当于application.getAttribute("userName") attr 用于按request > session > application顺序访问其属性(attribute) #attr.userName相当于按顺序在以上三个范围(scope)内读取userName属性,直到找到为止 - 用于过滤和投影(projecting)集合,如books.{?#this.price<100};
- 构造Map,如#{'foo1':'bar1', 'foo2':'bar2'}。
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Map;
- import javax.servlet.ServletContext;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.SessionAware;
- import org.apache.struts2.util.ServletContextAware;
- import tutorial.model.Book;
- import com.opensymphony.xwork2.ActionSupport;
- public class OgnlAction extends ActionSupport implements ServletRequestAware, SessionAware, ServletContextAware {
- private static final long serialVersionUID = 1L;
- private HttpServletRequest request;
- private Map<String, String> session;
- private ServletContext application;
- private List<Book> books;
- public void setServletRequest(HttpServletRequest request) {
- this.request = request;
- }
- @SuppressWarnings("unchecked")
- public void setSession(Map session) {
- this.session = session;
- }
- public void setServletContext(ServletContext application) {
- this.application = application;
- }
- public List<Book> getBooks() {
- return books;
- }
- @Override
- public String execute() {
- request.setAttribute("userName", "Max From request");
- session.put("userName", "Max From session");
- application.setAttribute("userName", "Max From application");
- books = new LinkedList<Book>();
- books.add(new Book("978-0735619678", "Code Complete, Second Edition", 32.99));
- books.add(new Book("978-0596007867", "The Art of Project Management", 35.96));
- books.add(new Book("978-0201633610", "Design Patterns: Elements of Reusable Object-Oriented Software", 43.19));
- books.add(new Book("978-0596527341", "Information Architecture for the World Wide Web: Designing Large-Scale Web Sites", 25.19));
- books.add(new Book("978-0735605350", "Software Estimation: Demystifying the Black Art", 25.19));
- return SUCCESS;
- }
- }
以上代码分别在request、session和application的范围内添加“userName”属性,然后再在JSP页面使用OGNL将其取回。
下面是Ognl.jsp的代码,内容如下:
- <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Struts OGNL Demo</title>
- </head>
- <body>
- <h3>访问OGNL上下文和Action上下文</h3>
- <p>parameters: <s:property value="#parameters.userName" /></p>
- <p>request.userName: <s:property value="#request.userName" /></p>
- <p>session.userName: <s:property value="#session.userName" /></p>
- <p>application.userName: <s:property value="#application.userName" /></p>
- <p>attr.userName: <s:property value="#attr.userName" /></p>
- <hr />
- <h3>用于过滤和投影(projecting)集合</h3>
- <p>Books more than $35</p>
- <ul>
- <s:iterator value="books.{?#this.price > 35}">
- <li><s:property value="title" /> - $<s:property value="price" /></li>
- </s:iterator>
- </ul>
- <p>The price of "Code Complete, Second Edition" is: <s:property value="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]"/></p>
- <hr />
- <h3>构造Map</h3>
- <s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />
- <p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>
- </body>
- </html>
以上代码值得注意的是“ <s:property value="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]"/> ”,因为“ books.{?#this.title=='Code Complete, Second Edition'}.{price} ”返回的值是集合类型,所以要用“[索引]”来访问其值。
Struts 2的配置文件struts.xml,内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <constant name="struts.devMode" value="true" />
- <package name="Struts2_OGNL_DEMO" extends="struts-default">
- <action name="Ognl" class="tutorial.action.OgnlAction">
- <result>/Ognl.jsp</result>
- </action>
- </package>
- </struts>
“%”符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值。例如在Ognl.jsp中加入以下代码:
- <hr />
- <h3>%的用途</h3>
- <p><s:url value="#foobar['foo1']" /></p>
- <p><s:url value="%{#foobar['foo1']}" /></p>
“$”有两个主要的用途:
- 用于在国际化资源文件中,引用OGNL表达式
- 在Struts 2配置文件中,引用OGNL表达式,如
- <action name="*index" class="org.han.action.HelloWorldAction"
- method="{1}">
- <result name="success">/index.jsp?uname=${message}</result>
- </action>
2.spring SpEL表达式语言:
本篇讲述了Spring Expression Language —— 即Spring3中功能丰富强大的表达式语言,简称SpEL。SpEL是类似于OGNL和JSF EL的表达式语言,能够在运行时构建复杂表达式,存取对象属性、对象方法调用等。所有的SpEL都支持XML和Annotation两种方式,格式:#{ SpEL expression }
一、 第一个Spring EL例子—— HelloWorld Demo
二、 Spring EL Method Invocation——SpEL 方法调用
三、 Spring EL Operators——SpEL 操作符
四、 Spring EL 三目操作符condition?true:false
五、 Spring EL 操作List、Map集合取值
一、 第一个Spring EL例子—— HelloWorld Demo
这个例子将展示如何利用SpEL注入String、Integer、Bean到属性中。
1. Spring El的依赖包
首先在Maven的pom.xml中加入依赖包,这样会自动下载SpEL的依赖。
文件:pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
2. Spring Bean
接下来写两个简单的Bean,稍后会用SpEL注入value到属性中。
Item.java如下:
package com.lei.demo.el;
public class Item {
private String name;
private int total;
//getter and setter...
}
Customer.java如下:
package com.lei.demo.el;
public class Customer {
private Item item;
private String itemName;
@Override
public String toString() {
return "itemName=" +this.itemName+" "+"Item.total="+this.item.getTotal();
}
//getter and setter...
}
3. Spring EL——XML
SpEL格式为#{ SpEL expression },xml配置见下。
文件:Spring-EL.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="itemBean" class="com.lei.demo.el.Item">
<property name="name" value="itemA" />
<property name="total" value="10" />
</bean>
<bean id="customerBean" class="com.lei.demo.el.Customer">
<property name="item" value="#{itemBean}" />
<property name="itemName" value="#{itemBean.name}" />
</bean>
</beans>
注解:
1. #{itemBean}——将itemBean注入到customerBean的item属性中。
2. #{itemBean.name}——将itemBean 的name属性,注入到customerBean的属性itemName中。
4. Spring EL——Annotation
SpEL的Annotation版本。
注意:要在Annotation中使用SpEL,必须要通过annotation注册组件。如果你在xml中注册了bean和在java class中定义了@Value,@Value在运行时将失败。
Item.java如下:
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("itemA")//直接注入String
private String name;
@Value("10")//直接注入integer
private int total;
//getter and setter...
}
Customer.java如下:
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{itemBean}")
private Item item;
@Value("#{itemBean.name}")
private String itemName;
//getter and setter...
}
Xml中配置组件自动扫描
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.lei.demo.el" />
</beans>
在Annotation模式中,用@Value定义EL。在这种情况下,直接注入一个String和integer值到itemBean中,然后注入itemBean到customerBean中。
5. 输出结果
App.java如下:
package com.lei.demo.el;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-EL.xml");
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
}
}
输出结果如下:itemName=itemA item.total=10
二、 Spring EL Method Invocation——SpEL 方法调用
SpEL允许开发者用El运行方法函数,并且允许将方法返回值注入到属性中。
1. Spring EL Method Invocation之Annotation
此段落演示用@Value注释,完成SpEL方法调用。
Customer.java如下:
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{'lei'.toUpperCase()}")
private String name;
@Value("#{priceBean.getSpecialPrice()}")
private double amount;
//getter and setter...省略
@Override
public String toString() {
return "Customer [name=" + name + ", amount=" + amount + "]";
}
}
Price.java如下:
package com.lei.demo.el;
import org.springframework.stereotype.Component;
@Component("priceBean")
public class Price {
public double getSpecialPrice() {
return new Double(99.99);
}
}
输出结果:Customer[name=LEI,amount=99.99]
上例中,以下语句调用toUpperCase()方法
@Value("#{'lei'.toUpperCase()}")
private String name;
上例中,以下语句调用priceBean中的getSpecialPrice()方法
@Value("#{priceBean.getSpecialPrice()}")
private double amount;
2. Spring EL Method Invocation之XML
在XMl中配置如下,效果相同
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="customerBean" class="com.leidemo.el.Customer">
<property name="name" value="#{'lei'.toUpperCase()}" />
<property name="amount" value="#{priceBean.getSpecialPrice()}" />
</bean>
<bean id="priceBean" class="com.lei.demo.el.Price" />
</beans>
三、 Spring EL Operators——SpEL 操作符
Spring EL 支持大多数的数学操作符、逻辑操作符、关系操作符。
1.关系操作符
包括:等于 (==, eq),不等于 (!=, ne),小于 (<, lt),,小于等于(<= , le),大于(>, gt),大于等于 (>=, ge)
2.逻辑操作符
包括:and,or,and not(!)
3.数学操作符
包括:加 (+),减 (-),乘 (*),除 (/),取模 (%),幂指数 (^)。
1. Spring EL Operators之Annotation
Numer.java如下
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("numberBean")
public class Number {
@Value("999")
private int no;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
Customer.java如下
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
//Relational operators
@Value("#{1 == 1}") //true
private boolean testEqual;
@Value("#{1 != 1}") //false
private boolean testNotEqual;
@Value("#{1 < 1}") //false
private boolean testLessThan;
@Value("#{1 <= 1}") //true
private boolean testLessThanOrEqual;
@Value("#{1 > 1}") //false
private boolean testGreaterThan;
@Value("#{1 >= 1}") //true
private boolean testGreaterThanOrEqual;
//Logical operators , numberBean.no == 999
@Value("#{numberBean.no == 999 and numberBean.no < 900}") //false
private boolean testAnd;
@Value("#{numberBean.no == 999 or numberBean.no < 900}") //true
private boolean testOr;
@Value("#{!(numberBean.no == 999)}") //false
private boolean testNot;
//Mathematical operators
@Value("#{1 + 1}") //2.0
private double testAdd;
@Value("#{'1' + '@' + '1'}") //1@1
private String testAddString;
@Value("#{1 - 1}") //0.0
private double testSubtraction;
@Value("#{1 * 1}") //1.0
private double testMultiplication;
@Value("#{10 / 2}") //5.0
private double testDivision;
@Value("#{10 % 10}") //0.0
private double testModulus ;
@Value("#{2 ^ 2}") //4.0
private double testExponentialPower;
@Override
public String toString() {
return "Customer [testEqual=" + testEqual + ", testNotEqual="
+ testNotEqual + ", testLessThan=" + testLessThan
+ ", testLessThanOrEqual=" + testLessThanOrEqual
+ ", testGreaterThan=" + testGreaterThan
+ ", testGreaterThanOrEqual=" + testGreaterThanOrEqual
+ ", testAnd=" + testAnd + ", testOr=" + testOr + ", testNot="
+ testNot + ", testAdd=" + testAdd + ", testAddString="
+ testAddString + ", testSubtraction=" + testSubtraction
+ ", testMultiplication=" + testMultiplication
+ ", testDivision=" + testDivision + ", testModulus="
+ testModulus + ", testExponentialPower="
+ testExponentialPower + "]";
}
}
运行如下代码:
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
结果如下:
Customer [ testEqual=true, testNotEqual=false, testLessThan=false, testLessThanOrEqual=true, testGreaterThan=false, testGreaterThanOrEqual=true, testAnd=false, testOr=true, testNot=false, testAdd=2.0, testAddString=1@1, testSubtraction=0.0, testMultiplication=1.0, testDivision=5.0, testModulus=0.0, testExponentialPower=4.0 ]
2. Spring EL Operators之XML
以下是等同的xml配置。
注意,类似小于号“<”,或者小于等于“<=”,在xml中是不直接支持的,必须用等同的文本表示方法表示,
例如,“<”用“lt”替换;“<=”用“le”替换,等等。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="customerBean" class="com.lei.demo.el.Customer">
<property name="testEqual" value="#{1 == 1}" />
<property name="testNotEqual" value="#{1 != 1}" />
<property name="testLessThan" value="#{1 lt 1}" />
<property name="testLessThanOrEqual" value="#{1 le 1}" />
<property name="testGreaterThan" value="#{1 > 1}" />
<property name="testGreaterThanOrEqual" value="#{1 >= 1}" />
<property name="testAnd" value="#{numberBean.no == 999 and numberBean.no lt 900}" />
<property name="testOr" value="#{numberBean.no == 999 or numberBean.no lt 900}" />
<property name="testNot" value="#{!(numberBean.no == 999)}" />
<property name="testAdd" value="#{1 + 1}" />
<property name="testAddString" value="#{'1' + '@' + '1'}" />
<property name="testSubtraction" value="#{1 - 1}" />
<property name="testMultiplication" value="#{1 * 1}" />
<property name="testDivision" value="#{10 / 2}" />
<property name="testModulus" value="#{10 % 10}" />
<property name="testExponentialPower" value="#{2 ^ 2}" />
</bean>
<bean id="numberBean" class="com.lei.demo.el.Number">
<property name="no" value="999" />
</bean>
</beans>
四、 Spring EL 三目操作符condition?true:false
SpEL支持三目运算符,以此来实现条件语句。
1. Annotation
Item.java如下:
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("99")
private int qtyOnHand;
public int getQtyOnHand() {
return qtyOnHand;
}
public void setQtyOnHand(int qtyOnHand) {
this.qtyOnHand = qtyOnHand;
}
}
Customer.java如下:
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{itemBean.qtyOnHand < 100 ? true : false}")
private boolean warning;
public boolean isWarning() {
return warning;
}
public void setWarning(boolean warning) {
this.warning = warning;
}
@Override
public String toString() {
return "Customer [warning=" + warning + "]";
}
}
输出:Customer [warning=true]
2. XMl
Xml配置如下,注意:应该用“<;”代替小于号“<”
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="customerBean" class="com.lei.demo.el.Customer">
<property name="warning"
value="#{itemBean.qtyOnHand < 100 ? true : false}" />
</bean>
<bean id="itemBean" class="com.lei.demo.el.Item">
<property name="qtyOnHand" value="99" />
</bean>
</beans>
输出:Customer [warning=true]
五、 Spring EL 操作List、Map集合取值
此段演示SpEL怎样从List、Map集合中取值,简单示例如下:
//get map where key = 'MapA' @Value("#{testBean.map['MapA']}") private String mapA; //get first value from list, list is 0-based. @Value("#{testBean.list[0]}") private String list;
1. Annotation
首先,创建一个HashMap和ArrayList,并初始化一些值。
Test.java如下:
package com.lei.demo.el;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
@Component("testBean")
public class Test {
private Map<String, String> map;
private List<String> list;
public Test() {
map = new HashMap<String, String>();
map.put("MapA", "This is A");
map.put("MapB", "This is B");
map.put("MapC", "This is C");
list = new ArrayList<String>();
list.add("List0");
list.add("List1");
list.add("List2");
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
然后,用SpEL取值,Customer.java如下
package com.lei.demo.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{testBean.map['MapA']}")
private String mapA;
@Value("#{testBean.list[0]}")
private String list;
public String getMapA() {
return mapA;
}
public void setMapA(String mapA) {
this.mapA = mapA;
}
public String getList() {
return list;
}
public void setList(String list) {
this.list = list;
}
@Override
public String toString() {
return "Customer [mapA=" + mapA + ", list=" + list + "]";
}
}
调用代码如下:
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
输出结果:Customer [mapA=This is A, list=List0]
2. XML
Xml配置如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="customerBean" class="com.lei.demo.el.Customer">
<property name="mapA" value="#{testBean.map['MapA']}" />
<property name="list" value="#{testBean.list[0]}" />
</bean>
<bean id="testBean" class="com.lei.demo.el.Test" />
</beans>
3.JSTL 核心标签库 使用
JSTL 核心标签库标签共有13个,功能上分为4类:
1.表达式控制标签:out、set、remove、catch
2.流程控制标签:if、choose、when、otherwise
3.循环标签:forEach、forTokens
4.URL操作标签:import、url、redirect
使用标签时,一定要在jsp文件头加入以下代码:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
下面分别对这些标签进行说明:
1. <c:out> 用来显示数据对象(字符串、表达式)的内容或结果
使用Java脚本的方式为:<% out.println("hello") %> <% =表达式 %>
使用JSTL标签:<c:out value="字符串">,例如:
<body>
<c:out value="<要显示的数据对象(未使用转义字符)>" escapeXml="true" default="默认值"></c:out><br/>
<c:out value="<要显示的数据对象(使用转义字符)>" escapeXml="false" default="默认值"></c:out><br/>
<c:out value="${null}" escapeXml="false">使用的表达式结果为null,则输出该默认值</c:out><br/>
</body>那么网页显示效果为:
2. <c:set> 用于将变量存取于 JSP 范围中或 JavaBean 属性中。下面的例子中假设已经有 Person.java 这个类文件。
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@page contentType="text/html; charset=utf-8" %>
<jsp:useBean id="person" class="lihui.Person"></jsp:useBean>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JSTL测试</title>
</head>
<body>
<c:set value="张三" var="name1" scope="session"></c:set>
<c:set var="name2" scope="session">李四</c:set>
<c:set value="赵五" target="${person}" property="name"></c:set>
<c:set target="${person}" property="age">19</c:set>
<li>从session中得到的值:${sessionScope.name1}</li>
<li>从session中得到的值:${sessionScope.name2}</li>
<li>从Bean中获取对象person的name值:<c:out value="${person.name}"></c:out></li>
<li>从Bean中获取对象person的age值:<c:out value="${person.age}"></c:out></li>
</body>
</html>一共有四种语法格式,前两种是给jsp的范围变量赋值,后两个是给 javabean 变量赋值
效果如下:
3.<c:remove> 主要用来从指定的 jsp 范围内移除指定的变量。使用类似,下面只给出语法:
<c:remove var="变量名" [scope="page|request|session|application"]></c:remove>
4.<c:catch> 用来处理 JSP 页面中产生的异常,并存储异常信息<c:catch var="name1">
容易产生异常的代码
</c:catch>
如果抛异常,则异常信息保存在变量 name1 中。
5.<c:if>
<c:if test="条件1" var="name" [scope="page|request|session|application"]></c:remove>
例:
<body>
<c:set value="赵五" target="${person}" property="name"></c:set>
<c:set target="${person}" property="age">19</c:set>
<c:if test="${person.name == '赵武'}" var="name1"></c:if>
<c:out value="name1的值:${name1}"></c:out><br/>
<c:if test="${person.name == '赵五'}" var="name2"></c:if>
<c:out value="name2的值:${name2}"></c:out>
</body>效果:
6. <c:choose> <c:when> <c:otherwise> 三个标签通常嵌套使用,第一个标签在最外层,最后一个标签在嵌套中只能使用一次
例:
<c:set var="score">85</c:set>
<c:choose>
<c:when test="${score>=90}">
你的成绩为优秀!
</c:when>
<c:when test="${score>=70&&score<90}">
您的成绩为良好!
</c:when>
<c:when test="${score>60&&score<70}">
您的成绩为及格
</c:when>
<c:otherwise>
对不起,您没有通过考试!
</c:otherwise>
</c:choose>7.<c:forEach>
语法:<c:forEach var="name" items="Collection" varStatus="statusName" begin="begin" end="end" step="step"></c:forEach>
该标签根据循环条件遍历集合 Collection 中的元素。 var 用于存储从集合中取出的元素;items 指定要遍历的集合;varStatus 用于存放集合中元素的信息。varStatus 一共有4种状态属性,下面例子中说明:
View Code显示效果:
8.<c:forTokens> 用于浏览字符串,并根据指定的字符串截取字符串
语法:<c:forTokens items="stringOfTokens" delims="delimiters" [var="name" begin="begin" end="end" step="len" varStatus="statusName"]></c:forTokens>还是看个例子吧:
View Code显示结果:
9.URL 操作标签
(1)<c:import> 把其他静态或动态文件包含到 JSP 页面。与<jsp:include>的区别是后者只能包含同一个web应用中的文件,前者可以包含其他web应用中的文件,甚至是网络上的资源。
语法:<c:import url="url" [context="context"] [value="value"] [scope="..."] [charEncoding="encoding"]></c:import>
<c:import url="url" varReader="name" [context="context"][charEncoding="encoding"]></c:import>
看个例子:
View Code显示结果:
URL路径有个绝对路径和相对路径。相对路径:<c:import url="a.txt"/>那么,a.txt必须与当前文件放在同一个文件目录下。如果以"/"开头,表示存放在应用程序的根目录下,如Tomcat应用程序的根目录文件夹为 webapps。导入该文件夹下的 b.txt 的编写方式: <c:import url="/b.txt">。如果要访问webapps管理文件夹中的其他Web应用,就要用context属性。例如访问demoProj下的index.jsp,则:<c:import url="/index.jsp" context="/demoProj"/>.
(2)<c:redirect> 该标签用来实现请求的重定向。例如,对用户输入的用户名和密码进行验证,不成功则重定向到登录页面。或者实现Web应用不同模块之间的衔接
语法:<c:redirect url="url" [context="context"]/>
或:<c:redirect url="url" [context="context"]>
<c:param name="name1" value="value1">
</c:redirect>
看个例子:
1 <%@ page contentType="text/html;charset=GBK"%>
2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3 <c:redirect url="http://127.0.0.1:8080">
4 <c:param name="uname">lihui</c:param>
5 <c:param name="password">11111</c:param>
6 </c:redirect>则运行后,页面跳转为:http://127.0.0.1:8080/?uname=lihui&password=11111
(3)<c:url> 用于动态生成一个 String 类型的URL,可以同上个标签共同使用,也可以使用HTML的<a>标签实验超链接。
语法:<c:url value="value" [var="name"] [scope="..."] [context="context"]>
<c:param name="name1" value="value1">
</c:url>
或:<c:url value="value" [var="name"] [scope="..."] [context="context"]/>
看个例子:
View Code显示: