• EL表达式的使用


    一:概要理解:

    (1)语法格式:
            ${表达式}

    (2)作用:
        El表达式一般支持作用域(application、session、request、pagecontext)中的属性。EL变量只支持某一作用域中的属性。

        注意:EL表达式不能操作局部变量

    (3)优点:
    表达式内容为对象时不需要导包
    可以实现变量类型的自动转换
    表达式可以被Jsp注释注释掉
    属性值读取不到时不会出错

    (4)注意事项及特殊应用
    取值顺序
        对不同作用域的同名属性进行取值时,顺序是从小到大的顺序

    (5)跨作用域取值
        ${作用域.属性名}
            作用域包含:pageScope、request.Scope、sessionScope、applicationScope

            注意:如果指定了作用域,就只能从特定的作用域进行取值
    (6)获取请求参数
        ${param.参数名}
        ${paramValues.参数名[索引下标] }

            注意:如果不使用param将从作用域中取值

    (7)访问javaBean的属性
         ${对象名.属性名}


     案例1:


    FirstServlet.java:

    package com.bjsxt.el.web;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import com.bjsxt.el.bean.Addr;
    import com.bjsxt.el.bean.User;

    public class FirstServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            
            String uname=req.getParameter("uname");
            String pwd=req.getParameter("pwd");
            String fav[]=req.getParameterValues("fav");
            
            //信息输出
            System.out.println("前台参数信息为:"+uname+"--->"+pwd+"--->"+fav[1]);
            
            //往request作用域存值
            req.setAttribute("realname", "lulu");
            
            //引入容器  ArrayList   HashMap
            List<String> list=new ArrayList<String>();
            
            list.add("aa");
            list.add("bb");
            list.add("cc");
            list.add("dd");
            req.setAttribute("list", list);
            
            Map<String,String> map=new HashMap<String,String>();
            map.put("xx", "110");
            map.put("yy", "114");
            map.put("zz", "119");
            map.put("11", "120");
            req.setAttribute("map", map);
            
            //引入真实应用场景
            //单个用户对象
            req.setAttribute("user", new User("moon", "123", "月亮", new Addr("BeiJing", "HaiDian", "XiSanQi")));
            
            //容器中多个user对象
            List<User> userList=new ArrayList<User>();
            userList.add(new User("sun", "123", "太阳", new Addr("BeiJing", "TongZhou", "yiZhuang1")));
            userList.add(new User("moon", "123", "月亮", new Addr("BeiJing", "HaiDian", "XiSanQi")));
            userList.add(new User("star", "123", "星星", new Addr("BeiJing", "HaiDian", "DongSanQi")));
            userList.add(new User("earth", "123", "地球", new Addr("BeiJing", "TongZhou", "yiZhuang2")));
            
            req.setAttribute("userList", userList);
            
            Map<String,User> userMap=new HashMap<String,User>();
            userMap.put("a", new User("sun", "123", "太阳", new Addr("BeiJing", "TongZhou", "yiZhuang1")));
            userMap.put("b", new User("star", "123", "星星", new Addr("BeiJing", "HaiDian", "DongSanQi")));
            userMap.put("c", new User("earth", "123", "地球", new Addr("BeiJing", "TongZhou", "yiZhuang2")));
            
            req.setAttribute("userMap", userMap);
            
            /*//额外的bug----没有解决
            Map<Integer,String> newMap=new HashMap<Integer,String>();
            newMap.put(new Integer(11), "110");
            newMap.put(new Integer("22"), "114");
            req.setAttribute("newMap", newMap);*/
            
            
            //跳转显示
            req.getRequestDispatcher("/el.jsp").forward(req, resp);
            return;
        }
    }

    el.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%-- <%@page  import="com.bjsxt.el.bean.*" %> --%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        <title>My JSP 'el.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
      </head>
     
      <body>
          <h2>EL表达式的使用</h2>
          <h5>EL:用于替换jsp中的java代码,使用时一切向美元"$"看</h5>
          <h5>EL:获取请求参数</h5>
          <h5>EL:获取作用域中的值</h5>
         <%--  <ol>
           <li><%=request.getParameter("uname") %> </li>
           <li><%=request.getParameter("pwd") %> </li>
           <li><%=request.getParameterValues("fav")[1] %> </li>
           <li><%=(String)request.getAttribute("realname") %> </li>
           <li><%=((List<String>)request.getAttribute("list")).get(1) %> </li>
           <li><%=((Map<String,String>)request.getAttribute("map")).get("xx") %> </li>
           <li><%=((User)request.getAttribute("user")).getAddr().getTown() %> </li>
           <li><%=((List<User>)request.getAttribute("userList")).get(2).getAddr().getTown() %></li>
           <li><%=((Map<String,User>)request.getAttribute("userMap")).get("c").getAddr().getTown() %></li>
          </ol> --%>
          <h3>EL写法</h3>
           <ol>
           <h5>使用EL获取请求参数</h5>
           <li>${param.uname }</li>
           <li>${param.pwd}</li>
           <li>${paramValues.fav[1]}</li>
           <h5>使用EL获取作用域的值</h5>
           <li>${realname}</li>
           <li>${list[1]}</li>
           <li>${map["xx"]}----</li>
           <h5>使用EL获取作用域中指定对象的属性值</h5>
           <li>${user.addr.town} </li>
           <h5>使用EL获取作用域中容器(List  Map)中对象的值</h5>
           <li>${userList[2].addr.town }</li>
           <li>${userMap.c.addr.town}---${userMap["c"].addr.town}</li>
          </ol>
      </body>
    </html>

    index.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
     
      <body>
        <h2>EL表达式的学习</h2>
         <ol>
           <li><a href="first?uname=momo&pwd=666&fav=1&fav=2&fav=3">El表达式1</a> </li>
           <li><a href="second">El表达式2</a> </li>
         </ol>
      </body>
    </html>

    案例2:

    Addr.java:

    package com.bjsxt.el.bean;

    public class Addr {
        private String province;
        private String city;
        private String town;
        public String getProvince() {
            return province;
        }
        public void setProvince(String province) {
            this.province = province;
        }
        public String getCity() {
            return city;
        }
        public void setCity(String city) {
            this.city = city;
        }
        public String getTown() {
            return town;
        }
        public void setTown(String town) {
            this.town = town;
        }
        @Override
        public String toString() {
            return "Addr [province=" + province + ", city=" + city + ", town=" + town + "]";
        }
        public Addr(String province, String city, String town) {
            super();
            this.province = province;
            this.city = city;
            this.town = town;
        }
        public Addr() {
            super();
        }
        
        
    }

    User.java:

    package com.bjsxt.el.bean;

    public class User {
        private String uname;
        private String pwd;
        private String realName;
        private Addr addr;
        public String getUname() {
            return uname;
        }
        public void setUname(String uname) {
            this.uname = uname;
        }
        public String getPwd() {
            return pwd;
        }
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
        public String getRealName() {
            return realName;
        }
        public void setRealName(String realName) {
            this.realName = realName;
        }
        public Addr getAddr() {
            return addr;
        }
        public void setAddr(Addr addr) {
            this.addr = addr;
        }
        @Override
        public String toString() {
            return "User [uname=" + uname + ", pwd=" + pwd + ", realName=" + realName + ", addr=" + addr + "]";
        }
        public User(String uname, String pwd, String realName, Addr addr) {
            super();
            this.uname = uname;
            this.pwd = pwd;
            this.realName = realName;
            this.addr = addr;
        }
        public User() {
            super();
        }
    }

    SecondServlet.java:

    package com.bjsxt.el.web;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import com.bjsxt.el.bean.Addr;
    import com.bjsxt.el.bean.User;

    public class SecondServlet extends HttpServlet {
        
        
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           
            //往作用域中存值
            req.setAttribute("hello", "request");
            req.getSession().setAttribute("hello", "session");
            this.getServletContext().setAttribute("hello", "application");
            
            
            req.setAttribute("user", new User("moon", "123", "月亮", new Addr("BeiJing", "HaiDian", "XiSanQi")));
            req.setAttribute("field", "realName");
            
            
            req.setAttribute("e1", " ");
            req.setAttribute("e2", null);
            req.setAttribute("e3", new ArrayList());
            req.setAttribute("e4", new HashMap());
            
            //跳转显示
            req.getRequestDispatcher("el2.jsp").forward(req, resp);
            return;
        }

    }

    el2.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>

    <%
     pageContext.setAttribute("hello", "pageContext");
     
      String  game="cf";
    %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'el2.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">

      </head>
     
      <body>
           <h2>El表达式从作用域中获取值的顺序?--->从小到大</h2>
           ${hello}-----pageContext----request---session---application
           
           <h2>El表达式如何实现跨作用域中取值?---->加入指定的作用域名即可,如requestScope</h2>
           ${pageScope.hello}-- ${requestScope.hello} ---${sessionScope.hello}---${applicationScope.hello}
           
           <h2>El表达式能否操作局部变量?---->el不能操作</h2>
           ++${game} ------<%=game %>
           
           <h2>空的判断</h2>
           ${empty  e1}
           ${empty  e2}
           ${empty  e3}
           ${empty  e4}
           <h2>"."方式和"[]"方式的区别?--->"."的方式简单方便,"[]"的功能较强大,但是还是推荐用“.”的方式</h2>
           ${user.realName}------${user["realName"] }----${field}----${user[field]}
           
           <h2>逻辑运算,注意,+不能用于字符串拼接,只能用于算术运算且注意,勿写为<%-- ${4+"a"} --%></h2>
           ${3+8}-----${3*9}-----${9/3} ---${12-6}----${1/0}----${3+"10"}---${"20"+23}---${2==3?"YES":"NO"}
           <h2>当作用域中没有改值的时候,用el获取值会不会报错?--->不会报错,也不会有所显示</h2>
           ${lol}========
      </body>
    </html>

    One who want to wear the crown. Bear the crown.
  • 相关阅读:
    Ambari部署问题 no schema has been selected to create in … error 解决方案
    redis命令效率分析
    linux测试上下行最大网速和实时网速
    springcloud之Zuul网关服务
    springcloud之Hystrix实现容错处理
    springcloud之Feign实现声明式REST调用
    springcloud之Ribbon负载均衡
    论meta name= viewport content= width=device-width initial-scale=1 minimum-scale=1 maximum-scale=1的作用
    for循环,绑定点击事件,二维数组列表渲染
    WebApp 里Meta标签大全,webappmeta标签大全
  • 原文地址:https://www.cnblogs.com/z0228-0322x/p/6180906.html
Copyright © 2020-2023  润新知