jsp表达式语言 总结

来源:互联网 发布:淘宝秒杀之如来神掌 编辑:程序博客网 时间:2024/05/16 19:10

jsp默认使用的表达式语言:EL表达式,可以直接使用;

struts2的默认表达式语言:OGNL; 简称 s标签

spring中默认的表达式语言:SpEL; 注:spring 3.0 中新增 , spring 3.0之前使用jstl

Apach开源jstl标签库:简称 c标签


1.OGNL的好处以及特点

Struts 2支持以下几种表达式语言:

  1. OGNL(Object-Graph Navigation Language),可以方便地操作对象属性的开源表达式语言;
  2. JSTL(JSP Standard Tag Library),JSP 2.0集成的标准的表达式语言;
  3. Groovy,基于Java平台的动态语言,它具有时下比较流行的动态语言(如Python、Ruby和Smarttalk等)的一些起特性;
  4. Velocity,严格来说不是表达式语言,它是一种基于Java的模板匹配引擎,具说其性能要比JSP好。

Struts 2默认的表达式语言是OGNL,原因是它相对其它表达式语言具有下面几大优势:

  1. 支持对象方法调用,如xxx.doSomeSpecial();
  2. 支持类静态的方法调用和值访问,表达式的格式为@[类全名(包括包路径)]@[方法名 |  值名],例如:@java.lang.String@format('foo %s', 'bar')或@tutorial.MyConstant@APP_NAME;
  3. 支持赋值操作和表达式串联,如price=100, discount=0.8, calculatePrice(),这个表达式会返回80;
  4. 访问OGNL上下文(OGNL context)和ActionContext;
  5. 操作集合对象。

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),如下面代码所示:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app id="WebApp_9" version="2.4"  
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  6.   
  7.     <display-name>Struts 2 OGNL</display-name>  
  8.       
  9.     <filter>  
  10.         <filter-name>struts-cleanup</filter-name>  
  11.         <filter-class>  
  12.             org.apache.struts2.dispatcher.ActionContextCleanUp  
  13.         </filter-class>  
  14.     </filter>  
  15.       
  16.     <filter-mapping>  
  17.         <filter-name>struts-cleanup</filter-name>  
  18.         <url-pattern>/*</url-pattern>  
  19.     </filter-mapping>  
  20.       
  21.     <filter>  
  22.         <filter-name>struts2</filter-name>  
  23.         <filter-class>  
  24.             org.apache.struts2.dispatcher.FilterDispatcher  
  25.         </filter-class>  
  26.     </filter>  
  27.   
  28.     <filter-mapping>  
  29.         <filter-name>struts2</filter-name>  
  30.         <url-pattern>/*</url-pattern>  
  31.     </filter-mapping>  
  32.   
  33.     <welcome-file-list>  
  34.         <welcome-file>index.html</welcome-file>  
  35.     </welcome-file-list>  
  36.   
  37. </web-app>  

“#”主要有三种用途:

  1. 访问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属性,直到找到为止
  2. 用于过滤和投影(projecting)集合,如books.{?#this.price<100};
  3. 构造Map,如#{'foo1':'bar1', 'foo2':'bar2'}。
下面让我们它们的具体写法,首先是Action类代码:

[java] view plaincopy
  1. import java.util.LinkedList;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4.   
  5. import javax.servlet.ServletContext;  
  6. import javax.servlet.http.HttpServletRequest;  
  7.   
  8. import org.apache.struts2.interceptor.ServletRequestAware;  
  9. import org.apache.struts2.interceptor.SessionAware;  
  10. import org.apache.struts2.util.ServletContextAware;  
  11.   
  12. import tutorial.model.Book;  
  13.   
  14. import com.opensymphony.xwork2.ActionSupport;  
  15.   
  16. public class OgnlAction extends ActionSupport implements ServletRequestAware, SessionAware, ServletContextAware  {  
  17.     private static final long serialVersionUID = 1L;  
  18.       
  19.     private HttpServletRequest request;  
  20.     private Map<String, String> session;  
  21.     private ServletContext application;  
  22.     private List<Book> books;  
  23.               
  24.     public void setServletRequest(HttpServletRequest request) {  
  25.         this.request = request;      
  26.     }  
  27.   
  28.     @SuppressWarnings("unchecked")  
  29.     public void setSession(Map session) {  
  30.         this.session = session;          
  31.     }  
  32.   
  33.     public void setServletContext(ServletContext application) {  
  34.         this.application = application;  
  35.     }  
  36.       
  37.     public List<Book> getBooks() {  
  38.         return books;  
  39.     }  
  40.   
  41.     @Override  
  42.     public String execute() {  
  43.         request.setAttribute("userName""Max From request");  
  44.         session.put("userName""Max From session");  
  45.         application.setAttribute("userName""Max From application");  
  46.           
  47.         books = new LinkedList<Book>();  
  48.         books.add(new Book("978-0735619678""Code Complete, Second Edition"32.99));  
  49.         books.add(new Book("978-0596007867""The Art of Project Management"35.96));  
  50.         books.add(new Book("978-0201633610""Design Patterns: Elements of Reusable Object-Oriented Software"43.19));  
  51.         books.add(new Book("978-0596527341""Information Architecture for the World Wide Web: Designing Large-Scale Web Sites"25.19));  
  52.         books.add(new Book("978-0735605350""Software Estimation: Demystifying the Black Art"25.19));  
  53.           
  54.         return SUCCESS;  
  55.     }  
  56. }  

以上代码分别在request、session和application的范围内添加“userName”属性,然后再在JSP页面使用OGNL将其取回。

下面是Ognl.jsp的代码,内容如下:

[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head>  
  7.     <title>Struts OGNL Demo</title>  
  8. </head>  
  9. <body>      
  10.     <h3>访问OGNL上下文和Action上下文</h3>  
  11.     <p>parameters: <s:property value="#parameters.userName" /></p>  
  12.     <p>request.userName: <s:property value="#request.userName" /></p>  
  13.     <p>session.userName: <s:property value="#session.userName" /></p>  
  14.     <p>application.userName: <s:property value="#application.userName" /></p>  
  15.     <p>attr.userName: <s:property value="#attr.userName" /></p>  
  16.     <hr />  
  17.     <h3>用于过滤和投影(projecting)集合</h3>  
  18.     <p>Books more than $35</p>  
  19.     <ul>  
  20.         <s:iterator value="books.{?#this.price > 35}">  
  21.             <li><s:property value="title" /> - $<s:property value="price" /></li>  
  22.         </s:iterator>  
  23.     </ul>  
  24.     <p>The price of "Code Complete, Second Edition" is: <s:property value="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]"/></p>  
  25.     <hr />  
  26.     <h3>构造Map</h3>  
  27.     <s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />  
  28.     <p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>  
  29. </body>  
  30. </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,内容如下:

[javascript] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <!DOCTYPE struts PUBLIC  
  4.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  5.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  6.   
  7. <struts>  
  8.     <constant name="struts.devMode" value="true" />  
  9.     <package name="Struts2_OGNL_DEMO" extends="struts-default">  
  10.         <action name="Ognl" class="tutorial.action.OgnlAction">  
  11.             <result>/Ognl.jsp</result>  
  12.         </action>          
  13.     </package>  
  14. </struts>  

“%”符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值。例如在Ognl.jsp中加入以下代码:

[html] view plaincopy
  1. <hr />  
  2.     <h3>%的用途</h3>  
  3.     <p><s:url value="#foobar['foo1']" /></p>  
  4.     <p><s:url value="%{#foobar['foo1']}" /></p>  

“$”有两个主要的用途:

  1. 用于在国际化资源文件中,引用OGNL表达式
  2. 在Struts 2配置文件中,引用OGNL表达式,如

[html] view plaincopy
  1. <action name="*index" class="org.han.action.HelloWorldAction"  
  2.     method="{1}">  
  3.     <result name="success">/index.jsp?uname=${message}</result>  
  4. </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注入到customerBeanitem属性中。

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配置如下,注意:应该用“&lt;”代替小于号“<”

复制代码
<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 &lt; 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.表达式控制标签:outsetremovecatch

2.流程控制标签:ifchoosewhenotherwise

3.循环标签:forEachforTokens

4.URL操作标签:importurlredirect

使用标签时,一定要在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="&lt要显示的数据对象(未使用转义字符)&gt" escapeXml="true" default="默认值"></c:out><br/>
<c:out value="&lt要显示的数据对象(使用转义字符)&gt" 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

显示:






0 0
原创粉丝点击