JavaWeb-JSTL与EL表达式

本文详细介绍了JavaWeb中的JSTL和EL表达式。EL(Expression Language)用于简化JSP输出,提供了四种内置作用域对象,并支持参数值输出。JSTL作为JSP标准标签库,旨在提升代码可读性和维护性,包括核心库、判断标签和遍历集合等功能。同时,文章还提到了fmt格式化标签库用于日期和数字的格式化。
摘要由CSDN通过智能技术生成

一、El表达式

Expression Language,表达式语言,用于简化JSP的输出

基本语法:${表达式}

示例:<h1>学生姓名:${student.name}</h1>

实例如下:

==========私有属性name,mobile,进行封装============

public class Student {

         private String name;

         private String mobile;


         public String getName() {

            return name;

         }

         public void setName(String name) {

            this.name = name;

         }

         public String getMobile() {

            return mobile;

         }

         public void setMobile(String mobile) {

            this.mobile = mobile;

        }

   }

===========Servlet初始化私有属性====================

Student stu = new Student();

stu.setName("子墨");

stu.setMobile(null);

String grade="A";

request.setAttribute("student", stu);

request.setAttribute("grade", grade);

request.getRequestDispatcher("/el_info.jsp").forward(request, response);
===========未使用el表达式的jsp=======================

<%

      Student stu=(Student)request.getAttribute("student");

      out.println("<h1>姓名:"+stu.getName()+"</h1>");

      out.println("<h1>手机:"+stu.getMobile()+"</h1>");

      String grade=(String)request.getAttribute("grade");

      out.println("<h1>教师评级:"+grade+"</h1>");

    %>

==========使用el表达式的jsp===方便,快捷,减少代码维护============

    <h1>姓名:${requestScope.student.name}</h1>

    <h1>电话:${requestScope.student.mobile} </h1>

    <h1>教师评级:${requestScope.grade} </h1>

二、EL作用域

  • EL表达式内置四种作用域对象
  • 忽略书写作用域对象时,el则按作用域从小到大依次尝试获取

作用域对象

描述

pageScope

从当前页面取值

requestScope

从当前请求中获取属性值

sessionScope

从当前会话中获取属性值

applicationScope

从当前应用获取全局属性值

实例:

========以sessionScope作用域对象为例===先初始化参数===========

         session.setAttribute("student", stu);

         session.setAttribute("grade", grade);

========以sessionScope作用域对象的JSP输出=================

    <!-- sessionScope作用域对象 -->

    <!--

    <h1>姓名:${sessionScope.student.name}</h1>

    <h1>电话:${sessionScope.student.mobile} </h1>

    <h1>教师评级:${sessionScope.grade} </h1>

    -->

    <!-- 可忽略作用域对象 -->

    <h1>姓名:${student.name}</h1>

    <h1>电话:${student.mobile} </h1>

    <h1>教师评级:${grade} </h1>

===========比较不写作用域对象会从哪个作用域获取值==========

request.setAttribute("garde", "B");//请求中

request.getServletContext().setAttribute("grade", "C");//全局中

HttpSession session=request.getSession();

PS:那当然是reuqestScope作用域咯,但是实际开发中最好是写出作用域对象,以免降低程序运行效率

三、EL表达式输出

语法:${[作用域.]属性名[.属性名]}

EL表达式支持将运算结果进行输出支持

EL支持绝大多数对象输出,本质是执行toSting()方法

作用:代替Servlet的out.println()

示例如上节:

${requestScope.student.name}

${sessionScope.student.name}

${student.name}

${5>3 }

四、EL输出参数值

EL表达式内置param对象来简化参数的输出

语法:${param.参数名}

示例:

<h1>讲师:${param.teacher }</h1>

等同于

String teacher=request.getParameter("teacher");

out.println("<h1>"+teacher+"</h1>");

五、JSTL标签库

  • JSTL(JSP Standard Tag Libaray),JSP标准标签库
  • JSTL用于简化JSP开发,提高代码的可读性与维护性
  • JSTL由SUN定义规范,由Apache Tomcat团队实现

1、下载JSTL标签库

官方地址:http://tomcat.apache.org

JSTL 组件介绍

作用域对象

描述

taglib-standard-spec-1.2.5.jar

标签库定义包(必须)

taglib-standard-impl-1.2.5.jar

标签库实现包(必须)

taglib-standard-jstlel-1.2.5.jar

el表达式支持包(备选)

taglib-standard-compact-1.2.5.jar

1.0版本兼容包(备选)

 

 

2、安装JSTL标签库

  • 将jar文件复制到工程的/WEB-INF/lib目录(推荐)
  • 将jar文件复制到Tomcat安装目录的lib目录

3、JSTL的标签库分类

按功能划分为5类

类别

核心标签库-core

格式化输出标签库-fmt

SQL操作标签库-sql(不用)

XML操作标签库-xml(不用)

函数标签库-functions(不用)

4、引用JSTL核心库

  • 核心标签库(Core)是JSTL最重要的标签库,提供了JSTL的基础功能
  • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  • JSTL核心标签库在taglib-standard-impl.jar由META-INF/c.tld定义

六、判断标签

提供两组判断标签

  • <c:if>-单分支判断
  • <c:choose>、<c:when>、<c:otherwise>-多分支判断

实例:

================servlet初始化参数================

request.setAttribute("score", 70);

request.setAttribute("grade", "D");

request.getRequestDispatcher("/core.jsp").forward(request, response);//请求转发

================JSP==========================

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<h1>成绩:${requestScope.score }</h1>

    <!-- if 单分支判断 -->

    <c:if test="${score >=60 }">

    <h1 style="color:red">恭喜及格了!</h1>

    </c:if>

    <c:if test="${score <60 }">

    <h1 style="color:yellow">再接再厉!</h1>

    </c:if>

    <!-- choose when otherwise 多分支判断 -->

    <h1>评级:${grade }</h1>

    <c:choose>

       <c:when test="${grade=='A' }">

          <h1 style="color:red">很优秀!</h1>

       </c:when>

       <c:when test="${grade=='B' }">

           <h1 style="color:red">不错哟!</h1>

       </c:when>

       <c:when test="${grade=='C' }">

           <h1 style="color:red">还需提高!</h1>

       </c:when>

       <c:otherwise>

          <h1 style="color:red">废物!</h1>

       </c:otherwise>

    </c:choose>

七、遍历集合

示例:

<c:forEach var="p" items="${persons}" varStatus="idx">

第${idx.index +1}位 <br/>

姓名:${p.name} 性别:${p.sex} 年龄:${p.age}

</c:forEach>

实例:

=============compay的Class文件部分代码=============

private String cname;

    private String url;

    
    public Company(String cname,String url) {

    this.cname=cname;

    this.url=url;

    }

============servlet的部分代码=========================

List<Company> list=new ArrayList<Company>();

list.add(new Company("腾讯","www.tencent.com"));

list.add(new Company("百度","www.baidu.com"));

list.add(new Company("慕课网","www.imooc.com"));

request.setAttribute("companies", list);

===================JSP的部分代码===================

<!--  forEach遍历数组

      List Companies=(List)request.getAttribute("companies",list);

      for(Company c:Companies){

          out.println("<h2>"+c.cname+":"+c.url+"</h2>");

      }

      items则是指数据源,var则是指迭代变量,varStatus则是指循环索引

    -->

    <c:forEach items="${requestScope.companies }" var="c" varStatus="idx">

         <h2>${idx.index+1 }:${c.cname }:${c.url }</h2>

    </c:forEach>

八、fmt格式化标签库

fmt格式化标签库 URL:http://java.sun.com/jsp/jstl/fmt

<fmt:formatDate value="" pattern="">格式化日期标签

<fmt:formatNumber value="" pattern="">格式化数字标签

对日期进行格式化的实例:

<!--

      formatDate pattern

      yyyy-四位年

      MM-月份

      dd-天

      HH-24小时制

      hh-12小时制

      mm-分钟

      ss-秒

      SSS-毫秒

     -->

    <fmt:formatDate value="${requestScope.now }" pattern="yyyy年MM月dd天HH时mm分ss秒SSS毫秒" />

对数值进行格式化的实例:

<h1><fmt:formatNumber  pattern="0,000.00" value="${requestScope.amt }"></fmt:formatNumber>元</h1>
<h2>null默认值:<c:out value="${nothing }" default="无"></c:out></h2>

    九、综合实例

===========employee类=====================

package com.imooc.employee;

public class Employee {

    private Integer empno;

    private String ename;

    private String department;

    private String job;

    private Float salary;   

public Employee(Integer empno, String ename, String department, String job, Float salary) {

super();

this.empno = empno;

this.ename = ename;

this.department = department;

this.job = job;

this.salary = salary;

}

public Integer getEmpno() {

return empno;

}

public void setEmpno(Integer empno) {

this.empno = empno;

}

public String getEname() {

return ename;

}

public void setEname(String ename) {

this.ename = ename;

}

public String getDepartment() {

return department;

}

public void setDepartment(String department) {

this.department = department;

}

public String getJob() {

return job;

}

public void setJob(String job) {

this.job = job;

}

public Float getSalary() {

return salary;

}

public void setSalary(Float salary) {

this.salary = salary;

}

}

================显示用的Servlet==============================

ServletContext context=request.getServletContext();

if(context.getAttribute("employees")==null) {

List<Employee> list=new ArrayList<Employee>();

Employee emp=new Employee(7731,"刘志敏","市场部","客户代表",10000f);

list.add(emp);

list.add(new Employee(8871,"张倩","研发部","运维工程师",8000f));

context.setAttribute("employees", list);

}

request.getRequestDispatcher("/employee.jsp").forward(request, response);

================新增用的Servlet==============================

request.setCharacterEncoding("UTF-8");

  String empno=request.getParameter("empno");

  String ename=request.getParameter("ename");

  String department=request.getParameter("department");

  String job=request.getParameter("job");

  String salary=request.getParameter("salary");

  System.out.println(empno);

  Employee emp=new Employee(Integer.parseInt(empno), ename, department, job, Float.parseFloat(salary));

  ServletContext context=request.getServletContext();

  @SuppressWarnings("unchecked")

List<Employee> employees =(List<Employee>)context.getAttribute("employees");

  employees.add(emp);

  context.setAttribute("employees", employees);

  request.getRequestDispatcher("/employee.jsp").forward(request, response);
===============employee.jsp页面==============================

<form action="/employee/create" method="post" >

                    <div class="form-group">

                        <label for="empno">员工编号</label>

                        <input type="text" name="empno" class="form-control" id="empno" placeholder="请输入员工编号">

                    </div>

                    <div class="form-group">

                        <label for="ename">员工姓名</label>

                        <input type="text" name="ename" class="form-control" id="ename" placeholder="请输入员工姓名">

                    </div>

                    <div class="form-group">

                        <label>部门</label>

                        <select id="dname" name="department" class="form-control">

                            <option selected="selected">请选择部门</option>

                            <option value="市场部">市场部</option>

                            <option value="研发部">研发部</option>

                        <option value="后勤部">后勤部</option>

                        </select>

                    </div>



                    <div class="form-group">

                        <label>职务</label>

                        <input type="text" name="job" class="form-control" id="sal" placeholder="请输入职务">

                    </div>



                    <div class="form-group">

                        <label for="sal">工资</label>

                        <input type="text" name="salary" class="form-control" id="sal" placeholder="请输入工资">

                    </div>



                    <div class="form-group" style="text-align: center;">

                        <button type="submit" class="btn btn-primary">保存</button>

                    </div>

                </form>



<c:forEach items="${applicationScope.employees }" var="emp" varStatus="idx">

                  <tr>

                    <td>${idx.index+1 }</td>

                    <td>${emp.empno }</td>

                    <td>${emp.ename }</td>

                    <td>${emp.department }</td>

                    <td>${emp.job }</td>

                    <td style="color: red;font-weight: bold">¥<fmt:formatNumber value="${emp.salary }" pattern="0,000.00"></fmt:formatNumber></td>

                </tr>

                </c:forEach>

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值