JSP中用el表达式获取数据示例

在JSP中我们要通过el表达式获取数据写法有:

1,在jsp页面中,通过${name}获取页面数据

    <% request.setAttribute("name","aaa");%>
    <!-- pageContext.findAttribute("name")   page request session application 相当于以下el表达式-->
    ${name } <!--输出 aaa-->

2,在jsp页面中,使用el表达式可以获取bean的属性

 <!-- 在jsp页面中,使用el表达式可以获取bean的属性 -->
    <% 
        Person p = new Person();
        p.setAge(12);
        request.setAttribute("person",p);
    %>
    ${person.age }

3,在jsp页面中,使用el表达式可以获取bean中的bean的属性

<% 
        Person person = new Person();
        Address address = new Address();
        person.setAddress(address);
        
        request.setAttribute("person",person);
    %>
    ${person.address.name }

4,在jsp页面中,使用el表达式获取list集合中指定位置的数据

<% 
        Person p1 = new Person();
        p1.setName("aa111");
        
        Person p2 = new Person();
        p2.setName("bb");
        
        List list = new ArrayList();
        list.add(p1);
        list.add(p2);
        
        request.setAttribute("list",list);
    %>
    
    ${list[0].name }

5, 在jsp页面中,使用el表达式获取map集合的数据

   <% 
        Map map = new HashMap();
        map.put("a","aaaaxxx");
        map.put("b","bbbb");
        map.put("c","cccc");
        
        map.put("1","aaaa1111");
        
        request.setAttribute("map",map);
   %>
    
    ${map.a }
    ${map["1"] }

6,利用el表达式获取web应用的名称:/MyWebStart

 <a href="${pageContext.request.contextPath }/1.jsp">点点</a>

注意:如果访问bean不存在的属性,会抛 Property 'username' not found on type ...

原文地址:https://www.cnblogs.com/lichone2010/p/3130110.html