首页 > 代码库 > [Java.web]EL表达式

[Java.web]EL表达式

<%@page import="cn.itcast.domain.Address"%>
<%@page import="cn.itcast.domain.Person"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML>
<html>
<head>
<title>el表达式和 jstl 快速入门</title>
</head>
<body>
    <%
        String data = "abcxx";
        request.setAttribute("data", data);
    %>
    ${ data }<br />
    <%--与下面的方法是一样的结果  --%>
    <%=pageContext.findAttribute("data")%><br />

    <%-- 在 Person 输入后按下 Alt + / 自动添加引用 --%>
    <%
        Person p = new Person();
        p.setName("aabxx");
        request.setAttribute("person", p);
    %>
    ${ person.name }<br />

    <%-- 在 Person 输入后按下 Alt + / 自动添加引用 --%>
    <%
        Person p2 = new Person();
        Address a = new Address();
        a.setCity("上海");
        p2.setAddress(a);
        request.setAttribute("person2", p2);
    %>
    ${ person2.address.city }<br />

    <%
        List list = new ArrayList();
        list.add(new Person("abc"));
        list.add(new Person("abcd"));
        list.add(new Person("abcde"));
        request.setAttribute("list", list);
    %>
    ${ list[1].name }<br /> 
    ${ list[2].name }<br />

    <%
        Map map = new HashMap();
        map.put("aa", new Person("abc"));
        map.put("bb", new Person("abcd"));
        map.put("cc", new Person("abcde"));
        map.put("dd", new Person("abcdef"));
        map.put("111", new Person("abcdefg"));
        request.setAttribute("map", map);
    %>
    ${ map.bb.name }<br />
    <%-- 遇到关键字是 数字 时,用 map[关键字‘] 来取值  --%>
    ${ map[111‘].name }<br />

    <%-- 取web应用名称 --%>
    ${ pageContext.request.contextPath }<br />
    <%-- 用它时不用以 / 为前缀 --%>
    <a href="${ pageContext.request.contextPath }">主页</a>
</body>
</html>

其中 Person 类是:

package cn.itcast.domain;

import java.util.Date;

public class Person {
    // Source -> Generate Constructors from Superclass 生成无参构造方法
    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }

    // Source -> Generate Constructors using Fields 生成有参的构造方法
    public Person(String name) {
        super();
        this.name = name;
    }

    private String name = "初始化值";
    private int age;
    private Date birthday;
    private Address address;
    
    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

[Java.web]EL表达式