目录
一、EL表达式:
1.简介:
- EL(Expression Language)表达式语言用于简化JSP的输出(多用于替换out.println()语句)。
- EL表达式的基本语法: ${表达式}
- 如 <h1> 学生姓名:${student.name} </h1>
例:
package com.el;
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;
}
}
package com.el;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class StudentServlet
*/
@WebServlet("/info")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public StudentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Student stu = new Student();
stu.setName("Isebal");
stu.setMobile(null);
String grade = "A";
request.setAttribute("student", stu);
request.setAttribute("grade", grade);
request.getRequestDispatcher("/info.jsp").forward(request, response); // 请求转发
}
}
info.jsp:
<%@page import="com.el.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- JSP版本:编写麻烦且难以调试和维护 -->
<%
Student stu = (Student) request.getAttribute("student");
String grade = (String) request.getAttribute("grade");
out.println("<h1>姓名:" + stu.getName() + "</h1>");
out.println("<h1>手机:" + stu.getMobile() + "</h1>");
out.println("<h2>教师评级:" + grade + "</h2>");
%>
<!-- EL版本 -->
<h1>姓名:${requestScope.student.name}</h1>
<h2>手机:${requestScope.student.mobile }</h2>
<h2>评级:${requestScope.grade }</h2>
</body>
</html>
其中,requesScope是EL表达式的作用域对象。
2.作用域对象:
- EL表达式内置四种作用域对象:
作用域对象 | 描述 |
pageScope | 从当前页面取值 |
requestScope | 从当前请求中获取属性值 |
sessionScope | 从当前会话中获取属性值 |
applicationScope | 从当前应用获取 全局属性值 |
- 注意作用域对象并不是强制要求书写的。当未书写作用域对象时,el 会按作用域由小到大依次尝试获取(但是自动匹配会降低程序的运行效率),写清楚更严谨。
3.EL表达式的输出:
- 语法:${[作用域.]属性名[.子属性名]}
- EL表达式支持输出运算结果。
- EL表达式支持输出绝大多数对象,本质是执行对象的toString()方法(故可修改toString()方法,来决定输出样式)。
例:
若在info.jsp中添加如下语句:
<h2>概要:${student}</h2>
输出一个对象,默认EL表达式要执行其toString()方法来转换成字符串打印在页面中。标准Java类的toString就是如图的格式。
修改,在Student.java类中重写tostring()方法:
@Override
public String toString() {
return name+":"+mobile;
}
还能看出一点,toString()若对一个空字符串输出,就会产生一个nul,而EL表达式只会输出一个空字符串,从而不会影响页面美观。
4.EL表达式输出传递的参数:
- EL表达式内置 param对象 来简化参数的输出。
- 语法:${param.参数名}
例:
在info.jsp中添加如下语句:
<h2>讲师:${param.teacher }</h2>
其实就是 request.getParameter() 的简化。
二、JSTL标签库 :
1.简介:
- JSTL(JSP Standard Tag Library)是JSP标准标签库。
- JSTL 用于简化JSP开发,提高代码的可读性和可维护性。
- JSTL 由SUN(Oracle)定义规范,由Apache Tomcat团队实现。
2.下载:
进入官方地址:http://tomcat.apache.org/
下拉,找到“Apache Standard Taglib 1.2.5 Released”,点击Download:
在新页面下拉找到如图,下载前2个:
3.安装:
JSTL有2种安装方式:
①将 jar 包复制到工程的 /WEB-INF/lib 目录(推荐),此时只会对该工程生效。
然后粘贴的jar 包会自动出现在 Web App Libraries 中,表示安装成功!
②将 jar 包复制到 Tomcat 安装目录的 lib 目录,对所有工程有效。
4.JSTL标签库的种类:
类别 |
核心标签库—— core |
格式化输出标签库—— fmt |
SQL 操作标签库—— sql |
XML 操作标签库—— xml |
函数标签库—— functions |
后3种已经不怎么用。
三、JSTL 核心标签库:
- 核心标签库(Core)是 JSTL 最重要的标签库,提供了 JSTL 的基础功能。
- 引用时,要在 JSP 页面上面(一般放在配置语句下面)书写如下指令:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- JSTL核心标签库在 taglibs-standard-impl.jar 由META-INF/c.tld 定义(META-INF 是元数据,用于描述标签的辅助信息。.tld 文件就是标签库的定义文件)。
1.判断标签:
JSTL核心标签库提供了两组判断的标签:
- 单分支判断:<c:if>
- 多分支判断:<c:choose>、<c:when>、<c:otherwise>
例:
JstlServlet.java:
package com.jstl;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class JstlServlet
*/
@WebServlet("/jstl")
public class JstlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JstlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("score", 100);
request.setAttribute("grade", "A");
request.getRequestDispatcher("/core.jsp").forward(request, response);
}
}
core.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 在Java或JSP文件中输入 Alt+/会出现智能提示 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${requestScope.score }</h1>
<c:if test="${score>=60 }">
<!-- EL表达式内部是布尔表达式 -->
<h1 style="color: green">恭喜,您已及格!</h1>
</c:if>
<c:if test="${score<60 }">
<h1 style="color: red">糟糕,您挂科了!</h1>
</c:if>
<!-- choose when otherwise -->
${grade }
<c:choose> <!-- 多支判断的根标签,必须要写 -->
<c:when test="${grade=='A'}">
<h2>优秀!</h2>
</c:when>
<c:when test="${grade=='B'}">
<h2>不错!</h2>
</c:when>
<c:when test="${grade=='C'}">
<h2>一般般!</h2>
</c:when>
<c:when test="${grade=='D'}">
<h2>有点差劲!</h2>
</c:when>
<c:otherwise>
<h2>尽力就好!</h2>
</c:otherwise>
</c:choose>
</body>
</html>
2.遍历集合:
- <c:forEach> 标签用于遍历集合中的每一个对象。
- 如:
<c:forEach var="p" items="${persons}" varStatus="idx">
第${idx.index+1}位 <br/>
姓名:${p.name} 性别:${p.sex} 年龄:${p.age}
</c:forEach>
<c:forEach> 标签的3个属性:
- items 表示数据源,会把数据源赋值给自定义变量(如 p)。
- varStatus 表示循环的状态变量。其属性index表示当前循环到第几行,从0开始。
- var 表示自定义变量。
例:
Company.java:
package com.jstl;
public class Company {
private String cname;
private String url;
public Company(String cname, String url) {
this.cname = cname;
this.url = url;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
JstlServlet.java:
package com.jstl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.org.apache.bcel.internal.generic.NEW;
/**
* Servlet implementation class JstlServlet
*/
@WebServlet("/jstl")
public class JstlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JstlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List list=new ArrayList();
list.add(new Company("淘宝", "https://www.taobao.com"));
list.add(new Company("百度", "https://www.baidu.com"));
list.add(new Company("4399", "http://www.4399.com"));
request.setAttribute("companies", list);
request.getRequestDispatcher("/core.jsp").forward(request, response);
}
}
core.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 在Java或JSP文件中输入 Alt+/会出现智能提示 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${requestScope.companies}" var="c" varStatus="idx">
<h2 style="color: green">${idx.index+1}.${c.cname }--${c.url }</h2>
</c:forEach>
</body>
</html>
四、fmt 格式化标签库:
- fmt 格式化标签库 URI:http://java.sun.com/jsp/jstl/fmt
- 格式化日期标签:<fmt:formatDate value="" pattern="">
- 格式化数字标签:<fmt:formatNumber value="" patten="">
例:
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setAttribute("amt", 20000105);
request.setAttribute("html", "<a href='index.html'>index</a>");
request.setAttribute("now", new Date());
request.setAttribute("nothing", null);
%>
<h2>${now }</h2>
<!--
formatDate pattern:
yyyy-四位年
MM-月
dd-两位日
HH-24小时制
hh-12小时制
mm-分钟
ss-秒数
SSS-毫秒
-->
<h2>
<fmt:formatDate value="${requestScope.now }"
pattern="yyyy年MM月dd日HH时mm分ss秒SSS毫秒" />
</h2>
<!-- 保留2位小数 -->
<h2>
<fmt:formatNumber value="${amt}" pattern="0.00"></fmt:formatNumber>
</h2>
<h2>
¥
<fmt:formatNumber value="${amt}" pattern="0,000.00"></fmt:formatNumber>
元
</h2>
<h2>
null默认值:
<c:out value="${nothing}" default="无"></c:out>
</h2>
<h2>
<c:out value="${html}" escapeXml="true"></c:out> <!-- escapeXml表示是否转义 -->
</h2>
</body>
</html>
五、综合案例:
Player.java:
package player;
import java.util.Date;
public class Player {
private String name;
private String age;
private String competition;
private String grade;
private Date date;
public Player(String name, String age, String competition, String grade, Date date) {
super();
this.name = name;
this.age = age;
this.competition = competition;
this.grade = grade;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCompetition() {
return competition;
}
public void setCompetition(String competition) {
this.competition = competition;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
ListServlet.java:
package player;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ListServlet1
*/
@WebServlet("/List")
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Player> list = new ArrayList<Player>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
Date date3 = null;
try {
date1 = dateFormat.parse("2021-7-29");
date2 = dateFormat.parse("2021-7-28");
date3 = dateFormat.parse("2021-7-30");
} catch (ParseException e) {
e.printStackTrace();
}
ServletContext context = request.getServletContext();
if (context.getAttribute("players") == null) {
Player player1 = new Player("陈梦", "27", "乒乓球 女子单打", "金牌", date1);
list.add(player1);
list.add(new Player("孙颖莎", "21", "乒乓球 女子单打", "银牌", date1));
list.add(new Player("肖若腾", "25", "竞技体操 男子全能", "银牌", date2));
list.add(new Player("汪顺", "27", "游泳 男子200米个人混合游", "金牌", date3));
context.setAttribute("players", list); //把列表存储在上下文对象
}
request.getRequestDispatcher("/player.jsp").forward(request, response);
}
}
player.jsp:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>员工列表</title>
<link href="css/bootstrap.css" type="text/css" rel="stylesheet"></link>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<style type="text/css">
.pagination {
margin: 0px
}
.pagination>li>a, .pagination>li>span {
margin: 0 5px;
border: 1px solid #dddddd;
}
.glyphicon {
margin-right: 3px;
}
.form-control[readonly] {
cursor: pointer;
background-color: white;
}
#dlgPhoto .modal-body {
text-align: center;
}
.preview {
max-width: 500px;
}
</style>
<script>
$(function() {
$("#btnAdd").click(function() {
$('#dlgForm').modal()
});
})
</script>
</head>
<body>
<div class="container">
<div class="row">
<h1 style="text-align: center">2021东京奥运会</h1>
<div class="panel panel-default">
<div class="clearfix panel-heading ">
<div class="input-group" style="width: 500px;">
<button class="btn btn-primary" id="btnAdd">
<span class="glyphicon glyphicon-zoom-in"></span>新增
</button>
</div>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
<th>比赛项目</th>
<th>成绩</th>
<th>比赛日期</th>
</tr>
</thead>
<tbody>
<c:forEach items="${applicationScope.players}" var="p"
varStatus="idx">
<tr>
<td>${idx.index+1 }</td>
<td>${p.name }</td>
<td>${p.age }</td>
<td>${p.competition }</td>
<td>${p.grade }</td>
<td style="color: red; font-weight: bold"><fmt:formatDate
value="${p.date }" pattern="yyyy年MM月dd日" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
<!-- 表单 -->
<div class="modal fade" tabindex="-1" role="dialog" id="dlgForm">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">新增运动员</h4>
</div>
<div class="modal-body">
<form action="/ZHALplayer/input" method="post">
<!-- 注意要写上ContextPath,通常就是工程名 -->
<div class="form-group">
<label for="name">运动员姓名</label> <input type="text" name="name"
class="form-control" id="name" placeholder="请输入运动员姓名">
</div>
<div class="form-group">
<label for="ename">运动员年龄</label> <input type="text" name="age"
class="form-control" id="age" placeholder="请输入运动员年龄">
</div>
<div class="form-group">
<label>比赛项目</label> <input type="text" name="competition"
class="form-control" id="competition" placeholder="请输入比赛项目">
</div>
<div class="form-group">
<label>成绩</label> <select id="grade" name="grade"
class="form-control">
<option selected="selected">请选择成绩</option>
<option value="金牌">金牌</option>
<option value="银牌">银牌</option>
<option value="铜牌">铜牌</option>
</select>
</div>
<div class="form-group">
<label>比赛日期</label> <select id="date" name="date"
class="form-control">
<option selected="selected">请选择比赛日期</option>
<option value="2021-7-28">2021-7-28</option>
<option value="2021-7-29">2021-7-29</option>
<option value="2021-7-30">2021-7-30</option>
</select>
</div>
<div class="form-group" style="text-align: center;">
<button type="submit" class="btn btn-primary">保存</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</body>
</html>
InputServlet.java:
package player;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
/**
* Servlet implementation class InputServlet
*/
@WebServlet("/input")
public class InputServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public InputServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); //因为post请求是无法处理中文
String name = request.getParameter("name");
String age = request.getParameter("age");
String competition = request.getParameter("competition");
String grade = request.getParameter("grade");
String date = request.getParameter("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
try {
date1 = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(name);
System.out.println(age);
System.out.println(competition);
System.out.println(grade);
System.out.println(date1);
Player player = new Player(name, age, competition, grade, date1);
ServletContext context = request.getServletContext();
// 把数据从原始的ServletContext中取出来
List<Player> list = (List<Player>) context.getAttribute("players");
// 更新数据
list.add(player);
// 再把数据放入ServletContext
context.setAttribute("players", list);
request.getRequestDispatcher("/player.jsp").forward(request, response);
}
}
注意关闭或重启项目时,增加的数据就会丢失。