目录
一、jsp的概述
1. JSP=Java Server Pages java服务器端页面
2. 程序员在开发过程中,发现Servlet做界面非常不方便,所以产生了jsp技术,JSP其实是对Servlet进行了包装而已。
3.jsp底层是基于Servlet封装, jsp + java类(service、javabean)+ servlet,就会构成mvc的开发模式,mvc模式是目前软件公司中相当通用的开发模式。
二、jsp的原理
1. jsp运行在服务器
2. jsp的基础是Servlet(相当于对Servlet进行了一个包装而已)
3. jsp就是根据: html + java片段 + JSP标签(语法) + javascript(css)
三、jsp的特点
1.JSP的全称是Java Server Pages,它和Servlet技术一样,都是SUN公司定义的一种用于开发动态web资源的技术。
2.jsp这门技术的最大的特点在于,写jsp就像在写HTML,但:它相对于html而言,html只能为用户提供静态数据,而jsp技术允许在页面中嵌套java代码,为用户提供动态数据。
3.相比Servlet而言,Servlet很难对数据进行排版,而jsp除了可以用java代码产生动态数据的同时,也很容易对数据进行排版。
四、jsp的入门
1. 指令
* 作用:用于配置JSP页面,导入资源文件
* 格式:
<%@ 指令名称 属性名1=属性值1 属性名2=属性值2 ... %>
* 分类:
1. page : 配置JSP页面的
* contentType:等同于response.setContentType()
1. 设置响应体的mime类型以及字符集
2. 设置当前jsp页面的编码(只能是高级的IDE才能生效,如果使用低级工具,则需要设置pageEncoding属性设置当前页面的字符集)
* import:导包
* errorPage:当前页面发生异常后,会自动跳转到指定的错误页面
* isErrorPage:标识当前也是是否是错误页面。
* true:是,可以使用内置对象exception
* false:否。默认值。不可以使用内置对象exception
2. include : 页面包含的。导入页面的资源文件
* <%@include file="top.jsp"%>
3. taglib : 导入资源
* <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
* prefix:前缀,自定义的
2. 注释:
1. html注释:
<!-- -->:只能注释html代码片段
2. jsp注释:推荐使用
<%-- --%>:可以注释所有
3. 内置对象
* 在jsp页面中不需要创建,直接使用的对象
* request
* response
* out:字符输出流对象。可以将数据输出到页面上。和response.getWriter()类似
* response.getWriter()和out.write()的区别:
* 在tomcat服务器真正给客户端做出响应之前,会先找response缓冲区数据,再找out缓冲区数据。
* response.getWriter()数据输出永远在out.write()之前
* 一共有9个:
变量名 | 变量名 | 作用 |
pageContext | PageContext | 当前页面共享数据,还可以获取其他八个内置对象 |
request | HttpServletRequest | 一次请求访问的多个资源(转发) |
session | HttpSession | 一次会话的多个请求间 |
application | ServletContext | 所有用户间共享数据 |
response | HttpServletResponse | 响应对象 |
page | Object | 当前页面(Servlet)的对象 this |
out | JspWriter | 输出对象,数据输出到页面上 |
config | ServletConfig | Servlet的配置对象 |
exception | Throwable | 异常对象 |
<%@ page import="java.util.Date" %><%--
Created by IntelliJ IDEA.
User: mayikt
Date: 2022/5/17
Time: 10:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户信息页面</title>
</head>
<body>
<h1>用户名称:{}</h1>
<a href="https://jiadian.jd.com/">家用电器</a>
<a href="https://shouji.jd.com/">手机数码</a>
<a href="https://channel.jd.com/furniture.html">家居家电</a>
<%
System.out.println("mayikt 666");
%>
</body>
</html>
package com.mayikt;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
resp.setContentType("text/html;charset=utf-8");
writer.println("<html>");
writer.println("<html>");
writer.println("<body>");
String userName = req.getParameter("userName");
writer.println("<h1>用户名称:{" + userName + "}</h1>");
writer.println("<a href=\"https://jiadian.jd.com/\">家用电器</a>");
writer.println("<a href=\"https://shouji.jd.com/\">手机数码</a>");
writer.println("<a href=\"https://channel.jd.com/furniture.html\">家居家电</a>");
writer.println("</body>");
System.out.println("6666");
writer.close();
}
}
五、jsp的脚本
jsp底层 基于servlet实现
在jsp中定义java代码
1.<% ... %>∶内容会直接放到_jspService()方法之中
2.<%=..%>∶内容会放到out.print()中,作为out.print()的参数
3.<%!...%>:内容会放到_jspService()方法之外,被类直接包含
<%--
Created by IntelliJ IDEA.
User: mayikt
Date: 2022/5/17
Time: 11:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>电商项目</title>
</head>
<body>
<h1>用户名称:{}</h1>
<a href="https://jiadian.jd.com/">家用电器</a>
<a href="https://shouji.jd.com/">手机数码</a>
<a href="https://channel.jd.com/furniture.html">家居家电</a>
<%
System.out.println("我是定义在jspservice方法之中....");
int j = 20;
mayikt();
%>
<%="直接输出 string类型 " + j %>
<%!
void mayikt() {
System.out.println("我是mayikt 我是定义在jspservice方法之外");
}
String userName = "mayikt";
%>
</body>
</html>
六、el表达式
1. 概念:Expression Language 表达式语言
2. 作用:替换和简化jsp页面中java代码的编写
3. 语法:${表达式}
4. 注意:
* jsp默认支持el表达式的。如果要忽略el表达式
1. 设置jsp中page指令中:isELIgnored="true" 忽略当前jsp页面中所有的el表达式
2. \${表达式} :忽略当前这个el表达式
5. 使用:
(1)运算:
* 运算符:
1. 算数运算符: + - * /(div) %(mod)
2. 比较运算符: > < >= <= == !=
3. 逻辑运算符: &&(and) ||(or) !(not)
4. 空运算符: empty
* 功能:用于判断字符串、集合、数组对象是否为null或者长度是否为0
* ${empty list}:判断字符串、集合、数组对象是否为null或者长度为0
* ${not empty str}:表示判断字符串、集合、数组对象是否不为null 并且 长度>0
(2) 获取值
a. el表达式只能从域对象中获取值
b. 语法:
(a) ${域名称.键名}:从指定域中获取指定键的值
* 域名称:
1. pageScope --> pageContext 当前页面有效
2. requestScope --> request 当前请求有效
3. sessionScope --> session 当前会话有效
4. applicationScope --> application(ServletContext) 当前应用有效
* 举例:在request域中存储了name=张三
* 获取:${requestScope.name}
(b) ${键名}:表示依次从最小的域中查找是否有该键对应的值,直到找到为止。
(3) 获取对象、List集合、Map集合的值
1. 对象:${域名称.键名.属性名}
* 本质上会去调用对象的getter方法
2. List集合:${域名称.键名[索引]}
3. Map集合:
* ${域名称.键名.key名称}
* ${域名称.键名["key名称"]}
6. 隐式对象:
* el表达式中有11个隐式对象
* pageContext:
* 获取jsp其他八个内置对象
* ${pageContext.request.contextPath}:动态获取虚拟目录
七、jstl标签
1. 概念:JavaServer Pages Tag Library JSP标准标签库
* 是由Apache组织提供的开源的免费的jsp标签 <标签>
2. 作用:用于简化和替换jsp页面上的java代码
3. 使用步骤:
1. 导入jstl相关jar包
2. 引入标签库:taglib指令:
<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
3. 使用标签
4. 常用的JSTL标签
1. if:相当于java代码的if语句
1. 属性:
* test 必须属性,接受boolean表达式
* 如果表达式为true,则显示if标签体内容,如果为false,则不显示标签体内容
* 一般情况下,test属性值会结合el表达式一起使用
2. 注意:
* c:if标签没有else情况,想要else情况,则可以在定义一个c:if标签
2. choose:相当于java代码的switch语句
1. 使用choose标签声明 相当于switch声明
2. 使用when标签做判断 相当于case
3. 使用otherwise标签做其他情况的声明 相当于default
3. foreach:相当于java代码的for语句
普通for循环:
*属性:
begin:开始值
end:结束值
var:临时变量
step:步长
varStatus:循环状态对象
index:容器中元素的索引,从o开始
count:循环次数,从1开始
增强for循环:
*属性:
items:容器对象
var :容器中元素的临时变量
varStatus :循环状态对象
index:容器中元素的索引,从o开始
count:循环次数,从1开始
apache对EL表达式的扩展(也就是说JSTL依赖EL),JSTL是标签语言!JSTL标签使用以来非常方便,它与JSP动作标签一样,只不过它不是JSP内置的标签,需要我们自己导包,以及指定标签库而已
f标签的test属性必须是一个boolean类型的值,如果test的值为true,那么执行if标签的内容,否则不执行。
<c:if test="${age>18}">
<h1>年龄大于18岁</h1>
</c:if>
<c:if test="${age<18}">
<h1>年龄小于18岁</h1>
</c:if>
<% if(age)>18 out.print("<h1>年龄大于18岁</h1>") %>
用于在JSP中显示数据,就像<%= ... > | |
用于保存数据 | |
用于删除数据 | |
用来处理产生错误的异常状况,并且将错误信息储存起来 | |
与我们在一般程序中用的if一样 | |
本身只当做<c:when>和<c:otherwise>的父标签 | |
<c:choose>的子标签,用来判断条件是否成立 | |
<c:choose>的子标签,接在<c:when>标签后,当<c:when>标签判断为false时被执行 | |
检索一个绝对或相对 URL,然后将其内容暴露给页面 | |
基础迭代标签,接受多种集合类型 | |
根据指定的分隔符来分隔内容并迭代输出 | |
用来给包含或重定向的页面传递参数 | |
重定向至一个新的URL. | |
使用可选的查询参数来创造一个URL |
jsp中 重点2个标签
<c:if>、<c:forEach>
八、 环境步骤
(1)导入JSTL的core标签库
(2)<%@ taglib prefix="c"uri="http://java.sun.com/jstl/core" %>
prefix="c":指定标签库的前缀,这个前缀可以随便给值,但大家都会在使用core标签库时指定前缀为c;
uri="http://java.sun.com/jstl/core":指定标签库的uri,它不一定是真实存在的网址,但它可以让JSP找到标签库的描述文件;
模板html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" align="center" style="border-collapse: collapse;width: 30%">
<tr align="center">
<th align="center">序号</th>
<th align="center">名称</th>
<th align="center">年龄</th>
<th align="center">冻结</th>
<th align="center">操作</th>
</tr>
<tr align="center">
<td align="center">0</td>
<td align="center">mayikt</td>
<td align="center">22</td>
<td align="center">未冻结</td>
<td align="center"><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
<tr align="center">
<td align="center">0</td>
<td align="center">lisi</td>
<td align="center">11</td>
<td align="center">未冻结</td>
<td align="center"><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
<tr align="center">
<td align="center">0</td>
<td align="center">xiaojun</td>
<td align="center">33</td>
<td align="center">冻结</td>
<td align="center"><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
<tr align="center">
<td align="center">0</td>
<td align="center">mayikt</td>
<td align="center">22</td>
<td align="center">未冻结</td>
<td align="center"><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</table>
</body>
</html>
package com.mayikt.servlet;
import com.mayikt.entity.UserEntity;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.jsp.jstl.fmt.LocalizationContext;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/userListServlet2")
public class UserListServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ArrayList<UserEntity> userEntities = new ArrayList<>();
userEntities.add(new UserEntity("mayikt", 22, 0));
userEntities.add(new UserEntity("meite", 32, 1));
userEntities.add(new UserEntity("xiaowei", 31, 0));
req.setAttribute("userEntities", userEntities);
req.getRequestDispatcher("userList.jsp").forward(req, resp);
}
}
package com.mayikt.entity;
public class UserEntity {
private String userName;
private Integer age;
private Integer state;
public UserEntity(String userName, Integer age, Integer state) {
this.userName = userName;
this.age = age;
this.state = state;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
(3)导入jar包
文档:javaweb开发相关资料下载.note
链接:有道云笔记
jsp 中定义c标签
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
九、MVC架构模式
1. jsp演变历史
1. 早期只有servlet,只能使用response输出标签数据,非常麻烦
2. 后来又jsp,简化了Servlet的开发,如果过度使用jsp,在jsp中即写大量的java代码,有写html表,造成难于维护,难于分工协作
3. 再后来,java的web开发,借鉴mvc开发模式,使得程序的设计更加合理性
2. MVC:
1. M:Model,模型。JavaBean
* 完成具体的业务操作,如:查询数据库,封装对象
2. V:View,视图。JSP
* 展示数据
3. C:Controller,控制器。Servlet
* 获取用户的输入
* 调用模型
* 将数据交给视图进行展示
MVC是一个架构模式,它强制性的使应用程序的输入、处理和输出分开。使用MVC应用程序被分成三个核心部件:模型、视图、控制器。他们各自处理自己的任务。
1.视图
视图是用户看到并与之交互的界面 jsp
2.模型
模型表示企业数据(数据模型:dao)和业务规划及操作(业务模型:service)
3.控制器
控制器表示用户的输入并调用模型和视图去完成用户的需求。
常见的MVC组件:Struts,Spring MVC,JSF
MVC架构模式
视图层
控制层
业务逻辑层
数据库访问层
十、案例:jsp+servlet+jdbc开发航班系统
需求分析
数据准备
CREATE TABLE `mayikt_flight` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'id列',
`flight_id` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '航号',
`company` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '航空公司',
`departure_airport` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '出发机场',
`arrive_airport` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '达到机场',
`departure_time` datetime DEFAULT NULL COMMENT '出发时间',
`arrive_time` datetime DEFAULT NULL COMMENT '到达时间',
`model` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '机型',
`is_delete` int DEFAULT NULL COMMENT '是否隐藏0显示 1隐藏',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb3;
测试数据
INSERT INTO `flight`.`mayikt_flight` (`id`, `flight_id`, `company`, `departure_airport`, `arrive_airport`, `departure_time`, `arrive_time`, `model`, `is_delete`) VALUES ('1', 'MYKT001', '中国东方航空公司', '武汉天河机场', '北京首都机场', '2022-05-20 03:08:24', '2022-05-21 03:08:31', '735', '0');
静态模板页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" align="center" style="border-collapse: collapse;width: 80%">
<tr align="center">
<th align="center">航号</th>
<th align="center">航空公司</th>
<th align="center">出发机场</th>
<th align="center">达到机场</th>
<th align="center">出发时间</th>
<th align="center">到达时间</th>
<th align="center">机型</th>
<th align="center">操作</th>
</tr>
<tr align="center">
<td align="center">MYKT001</td>
<td align="center">中国东方航空</td>
<td align="center">武汉天河机场</td>
<td align="center">北京首都机场</td>
<td align="center">2022年5月25日 12:00</td>
<td align="center">2022年5月25日 14:00</td>
<td align="center">735</td>
<td align="center"><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</table>
</body>
</html>
需要的相关依赖jar包
文档:javaweb开发相关资料下载.note
链接:有道云笔记
jdbc配置文件
config.properties
driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/flight?serverTimezone=UTC
user=root
password=root
工具类
public class MayiktJdbcUtils {
/**
* 1.需要将我们的构造方法私有化 ---工具类 不需要 new出来 是通过类名称.方法名称访问
*/
private MayiktJdbcUtils() {
}
/**
* 2.定义工具类 需要 声明 变量
*/
private static String driverClass;
private static String url;
private static String user;
private static String password;
/**
*3.使用静态代码快 来给我们声明好 jdbc变量赋值(读取config.properties)
*/
static {
try {
// 1.读取config.properties IO 路径 相对路径
InputStream resourceAsStream = MayiktJdbcUtils.class.getClassLoader().
getResourceAsStream("config.properties");
// 2.赋值给我们声明好的变量
Properties properties = new Properties();
properties.load(resourceAsStream);
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
// 3.注册驱动类
Class.forName(driverClass);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 4.封装连接方法
*/
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
/**
* 5.封装释放连接方法 (重载)
*/
public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection) {
// 1.查询 释放连接 resultSet statement connection
try {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 增删改---释放jdbc资源
*
* @param statement
* @param connection
*/
public static void closeConnection(Statement statement, Connection connection) {
// 1.查询 释放连接 resultSet statement connection
closeConnection(null, statement, connection);
}
/**
* 开启事务
*
* @param connection
* @throws SQLException
*/
public static void beginTransaction(Connection connection) throws SQLException {
connection.setAutoCommit(false);
}
/**
* 提交事务
*
* @param connection
* @throws SQLException
*/
public static void commitTransaction(Connection connection) throws SQLException {
connection.commit();
}
/**
* 回滚事务
*
* @param connection
*/
public static void rollBackTransaction(Connection connection) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭事务
*
* @param connection
*/
public static void endTransaction(Connection connection) {
if (connection != null) {
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
查询所有航班信息
实体类
public class FlightEntity {
/**
* CREATE TABLE `mayikt_flight` (
* `id` int NOT NULL AUTO_INCREMENT COMMENT 'id列',
* `flight_id` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '航号',
* `company` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '航空公司',
* `departure_airport` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '出发机场',
* `arrive_airport` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '达到机场',
* `departure_time` datetime DEFAULT NULL COMMENT '出发时间',
* `arrive_time` datetime DEFAULT NULL COMMENT '到达时间',
* `model` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '机型',
* `is_delete` int DEFAULT NULL COMMENT '是否隐藏0显示 1隐藏',
* PRIMARY KEY (`id`)
* ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb3;
*/
private Integer id;
private String flightId;
private String company;
private String departureAirport;
private String arriveAirport;
private Date departureTime;
private Date arriveTime;
private String model;
private Integer isDelete;
public FlightEntity(Integer id, String flightId, String company, String departureAirport, String arriveAirport, Date departureTime, Date arriveTime, String model, Integer isDelete) {
this.id = id;
this.flightId = flightId;
this.company = company;
this.departureAirport = departureAirport;
this.arriveAirport = arriveAirport;
this.departureTime = departureTime;
this.arriveTime = arriveTime;
this.model = model;
this.isDelete = isDelete;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFlightId() {
return flightId;
}
public void setFlightId(String flightId) {
this.flightId = flightId;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDepartureAirport() {
return departureAirport;
}
public void setDepartureAirport(String departureAirport) {
this.departureAirport = departureAirport;
}
public String getArriveAirport() {
return arriveAirport;
}
public void setArriveAirport(String arriveAirport) {
this.arriveAirport = arriveAirport;
}
public Date getDepartureTime() {
return departureTime;
}
public void setDepartureTime(Date departureTime) {
this.departureTime = departureTime;
}
public Date getArriveTime() {
return arriveTime;
}
public void setArriveTime(Date arriveTime) {
this.arriveTime = arriveTime;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
}
数据库访问层
public class FlightDao {
/**
* 查询所有的航班信息
*
* @return
*/
public List<FlightEntity> getByAll() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 1.获取连接
connection = MayiktJdbcUtils.getConnection();
//2.获取执行者对象
preparedStatement = connection.prepareStatement("select * from mayikt_flight");
resultSet = preparedStatement.executeQuery();
ArrayList<FlightEntity> flightEntities = new ArrayList<>();
while (resultSet.next()) {
Integer id = resultSet.getInt("id");
String flightId = resultSet.getString("flight_id");
String company = resultSet.getString("company");
String departureAirport = resultSet.getString("departure_airport");
String arriveAirport = resultSet.getString("arrive_airport");
Date departureTime = resultSet.getDate("departure_time");
Date arriveTime = resultSet.getDate("arrive_time");
String model = resultSet.getString("model");
Integer isDelete = resultSet.getInt("is_delete");
FlightEntity flightEntity = new FlightEntity(id, flightId, company, departureAirport, arriveAirport, departureTime, arriveTime, model,
isDelete);
// 存入到集合中
flightEntities.add(flightEntity);
}
return flightEntities;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放资源
MayiktJdbcUtils.closeConnection(resultSet, preparedStatement, connection);
}
}
}
业务逻辑层
package com.mayikt.service;
import com.mayikt.dao.FlightDao;
import com.mayikt.entity.FlightEntity;
import java.util.List;
public class FlightService {
// 业务逻辑调用数据库访问层获取数据
private FlightDao flightDao = new FlightDao();
/**
* 查询所有的航班信息
*
* @return
*/
public List<FlightEntity> getByAll() {
return flightDao.getByAll();
}
}
控制层
@WebServlet("/show")
public class FlightServlet extends HttpServlet {
private FlightService flightService = new FlightService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 控制层调用业务逻辑层获取数据
List<FlightEntity> flightEntitys = flightService.getByAll();
// 转发到jsp中
req.setAttribute("flights", flightEntitys);
req.getRequestDispatcher("show.jsp").forward(req, resp);
}
}
视图层
<%--
Created by IntelliJ IDEA.
User: mayikt
Date: 2022/5/20
Time: 18:26
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>航班系统</title>
</head>
<body>
<table border="1" align="center" style="border-collapse: collapse;width: 80%">
<tr align="center">
<th align="center">航号</th>
<th align="center">航空公司</th>
<th align="center">出发机场</th>
<th align="center">达到机场</th>
<th align="center">出发时间</th>
<th align="center">到达时间</th>
<th align="center">机型</th>
<th align="center">操作</th>
</tr>
<c:forEach items="${flights}" var="f">
<tr align="center">
<td align="center">${f.flightId}</td>
<td align="center">${f.company}</td>
<td align="center">${f.departureAirport}</td>
<td align="center">${f.arriveAirport}</td>
<td align="center">${f.departureTime}</td>
<td align="center">${f.arriveTime}</td>
<td align="center">${f.model}</td>
<td align="center"><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
修改航班信息
数据回显
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div >
<h1>修改数据</h1>
<form>
<label>航 号: <input type="text"></label><br>
<label>航空公司: <input type="text"></label><br>
<label>出发机场: <input type="text"></label><br>
<label>达到机场: <input type="text"></label><br>
<label>出发时间: <input type="text"></label><br>
<label>到达时间: <input type="text"></label><br>
<label>机 型: <input type="text"></label><br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
dao层
/**
* 根据id查询航班信息
*
* @return
*/
public FlightEntity getByIdFlight(Integer id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 1.获取连接
connection = MayiktJdbcUtils.getConnection();
//2.获取执行者对象
preparedStatement = connection.prepareStatement("select * from mayikt_flight where id=?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (!resultSet.next()) {
return null;
}
// 连接到db查询数据
Integer dbId = resultSet.getInt("id");
String flightId = resultSet.getString("flight_id");
String company = resultSet.getString("company");
String departureAirport = resultSet.getString("departure_airport");
String arriveAirport = resultSet.getString("arrive_airport");
Date departureTime = resultSet.getDate("departure_time");
Date arriveTime = resultSet.getDate("arrive_time");
String model = resultSet.getString("model");
Integer isDelete = resultSet.getInt("is_delete");
FlightEntity flightEntity = new FlightEntity(dbId, flightId, company, departureAirport, arriveAirport, departureTime, arriveTime, model,
isDelete);
return flightEntity;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放资源
MayiktJdbcUtils.closeConnection(resultSet, preparedStatement, connection);
}
}
业务逻辑层
public FlightEntity getByIdFlight(Integer id) {
return flightDao.getByIdFlight(id);
}
@WebServlet("/updateFlight")
public class UpdateFlightServlet extends HttpServlet {
private FlightService flightService = new FlightService();
/**
* doGet 用户点击修改该条数据-------需要查询到该条数据(回显)
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取需要修改的id值
String idStr = req.getParameter("id");
if (idStr == null || idStr == "") {
// 跳转到错误页面 客户端传递参数有问题
/// 转发到错误jsp中
req.setAttribute("errorMsg", "id的值是为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
try {
// mayikt1
Integer id = Integer.parseInt(idStr);
FlightEntity flightEntity = flightService.getByIdFlight(id);
if (flightEntity == null) {
/// 转发到错误jsp中
req.setAttribute("errorMsg", "该id在db中无法查询到数据");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
//转发到修改航班信息页面
req.setAttribute("flight", flightEntity);
req.getRequestDispatcher("updateFlight.jsp").forward(req, resp);
} catch (Exception e) {
req.setAttribute("errorMsg", "系统错误!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
}
}
/**
* 接受用户需要修改的数据
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
视图层
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改航班信息</title>
</head>
<body>
<div>
<h1>修改数据</h1>
<form>
<label>航 号: <input type="text" value="${flight.flightId}"></label><br>
<label>航空公司: <input type="text" value="${flight.company}"></label><br>
<label>出发机场: <input type="text" value="${flight.departureAirport}"></label><br>
<label>达到机场: <input type="text" value="${flight.arriveAirport}"></label><br>
<label>出发时间: <input type="text" value="${flight.departureTime}"></label><br>
<label>到达时间: <input type="text" value="${flight.arriveTime}"></label><br>
<label>机 型: <input type="text" value="${flight.model}"></label><br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
修改数据
工具类
public class DateUtils {
/**
* 预定的日期格式
*/
public static final String[] DATEFORMAT = {"yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss", "yyyy年MM月dd日HH时mm分ss秒", "yyyy-MM-dd", "yyyy/MM/dd", "yy-MM-dd", "yy/MM/dd", "yyyy年MM月dd日", "HH:mm:ss",
"yyyyMMddHHmmss", "yyyyMMdd", "yyyy.MM.dd", "yy.MM.dd", "yyyyMMddHHmmssSSS", "yyyy-MM-dd HH:mm:ss:SSS", "yyyy-MM-dd HH:mm:ss.SSS", "yyyy", "yyyyMM", "yyyyMMdd HH", "yyyyMMdd HH:mm",
"yyyyMMdd HH:mm:ss", "yyyy-MM" };
/**
* 线程绑定的日期格式转换器缓存
*/
private static final ThreadLocal<Map<String, SimpleDateFormat>> DATEFORMATERSCACHE = new ThreadLocal<Map<String, SimpleDateFormat>>();
/**
* 获取当前系统时间
*/
public static Calendar getSystemCurrentTime() {
final Calendar currentTime = Calendar.getInstance();
return currentTime;
}
/**
* 获取当前系统时间
*/
public static String getSystemCurrentTime(int format) {
return toDateStrByFormatIndex(getSystemCurrentTime(), format);
}
/**
* 获取系统当前date类型时间
*/
public static Date getCurrentDate() {
return new Date();
}
/**
* 获取系统当前日期和时间,格式为yyyy-MM-dd HH:mm:ss
*/
public static String getCurrentDateTime() {
return getFormatCurrentDate("yyyy-MM-dd HH:mm:ss");
}
/**
* 返回格式化的当前日期/时间
*/
public static String getFormatCurrentDate(String strFormat) {
return msFormatDateTime(getCurrentDate(), strFormat);
}
/**
* 日期/时间格式化显示(年、月、日、时、分、秒、毫秒、星期)
*/
public static String msFormatDateTime(Date dtmDate, String strFormat) {
if (strFormat.equals("")) {
strFormat = "yyyy-MM-dd HH:mm:ss";
}
final SimpleDateFormat myFormat = new SimpleDateFormat(strFormat);
return myFormat.format(dtmDate.getTime());
}
/**
* 日期/时间格式化显示(年、月、日)
*/
public static String msFormatDate(Date dtmDate, String strFormat) {
if (strFormat.equals("")) {
strFormat = "yyyy-MM-dd";
}
final SimpleDateFormat myFormat = new SimpleDateFormat(strFormat);
return myFormat.format(dtmDate.getTime());
}
/**
* 获取当前系统时间
*/
public static String getSystemCurrentTime(String format) {
return toDateStrByFormat(getSystemCurrentTime(), format);
}
// ======================日期转字符串基础格式化方法======================================================================================
/**
* @name 中文名称
*/
private static SimpleDateFormat getDateFormater(String format) {
Map<String, SimpleDateFormat> dateFormaters = DATEFORMATERSCACHE.get();
SimpleDateFormat dateFormater = null;
boolean formatersIsNull = false;
if (dateFormaters == null) {
dateFormaters = new HashMap<String, SimpleDateFormat>(3, 0.2f);
DATEFORMATERSCACHE.set(dateFormaters);
formatersIsNull = true;
}
dateFormater = dateFormaters.get(format);
if (formatersIsNull || dateFormater == null) {
dateFormater = new SimpleDateFormat(format);
dateFormaters.put(format, dateFormater);
}
return dateFormater;
}
private static SimpleDateFormat getDateFormater(int format) {
return getDateFormater(DATEFORMAT[format]);
}
// ======================日期转字符串基础方法======================================================================================
/**
*
* Calendar日期转指定日期格式的字符串
*/
public static String toDateStrByFormat(Calendar date, String format) {
if (date == null) {
return null;
}
return getDateFormater(format).format(date.getTime());
}
/**
*
* Calendar日期转指定日期格式的字符串
*/
public static String toDateStrByFormatIndex(Calendar date, int format) {
return toDateStrByFormat(date, DATEFORMAT[format]);
}
/**
* java.util.Date日期转指定日期格式的字符串
*/
public static String toDateStrByFormat(Date date, String format) {
if (date == null) {
return null;
}
return getDateFormater(format).format(date.getTime());
}
/**
* java.util.Date日期转指定格式的字符串
*/
public static String toDateStrByFormatIndex(Date date, int format) {
return toDateStrByFormat(date, DATEFORMAT[format]);
}
// ======================日期转字符串方法======================================================================================
/**
* Calendar日期转日期字符串
*/
public static String toDateTimeStr(Calendar date) {
return toDateStrByFormatIndex(date, 0);
}
/**
* Calendar日期转指定日期格式的字符串
*/
public static String toDateTimeStr(int format, Calendar date) {
return toDateStrByFormatIndex(date, format);
}
/**
* Calendar日期转日期字符串
*/
public static String toDateStr(Calendar date) {
return toDateStrByFormatIndex(date, 3);
}
/**
* java.util.Date日期转指定格式的日期字符串
*/
public static String dateToString(Date date, int format) {
return toDateStrByFormatIndex(date, format);
}
/**
* java.util.Date日期转日期字符串
*/
public static String dateToString(Date date) {
return toDateStrByFormatIndex(date, 3);
}
// ======================xx转Date方法======================================================================================
/**
* Calendar日期转java.util.Date日期
*/
public static Date convertCalendarToDate(Calendar c) {
final Date d = new Date();
d.setTime(c.getTimeInMillis());
return d;
}
/**
* 日期字符串转java.util.Date日期
*/
public static Date stringToDate(String dateStr) throws Exception {
return parseDate(dateStr, 3);
}
/**
* 日期字符串转指定格式的java.util.Date日期
*/
public static Date parseDate(String dateStr, int format) throws Exception {
if (dateStr == null || dateStr.length() == 0) {
return null;
}
try {
return getDateFormater(format).parse(dateStr);
} catch (ParseException ex) {
return parseDate(dateStr, format + 1);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new Exception("UT-07001:日志字符串" + dateStr + "格式不支持", ex);
}
}
// ======================xx转Calendar方法======================================================================================
/**
* java.util.Date转Calendar
*/
public static Calendar convUtilDateToUtilCalendar(Date date) {
if (date == null) {
return null;
}
final GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date.getTime());
return gc;
}
/**
* java.sql.Timestamp转Calendar
*/
public static Calendar convSqlTimestampToUtilCalendar(Timestamp date) {
if (date == null) {
return null;
}
final GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date.getTime());
return gc;
}
/**
* 日期字符串转Calendar
*/
public static Calendar parseDate(String dateStr) throws Exception {
final Date result = parseDate(dateStr, 0);
Calendar cal = null;
if (result != null) {
cal = new GregorianCalendar(0, 0, 0, 0, 0, 0);
cal.setTime(result);
}
return cal;
}
// ======================日期转Timestamp方法======================================================================================
/**
* java.util.Date转java.sql.Timestamp
*/
public static Timestamp convUtilDateToSqlTimestamp(Date date) {
if (date == null) {
return null;
}
return new Timestamp(date.getTime());
}
/**
* Calendar日期对象转Timestamp日期对象
*/
public static Timestamp convUtilCalendarToSqlTimestamp(Calendar date) {
if (date == null) {
return null;
}
return new Timestamp(date.getTimeInMillis());
}
/**
* Calendar日期对象转Timestamp日期对象
*/
public static Timestamp parseTimestamp(Calendar calendar) {
return new Timestamp(calendar.getTimeInMillis());
}
/**
* 日期字符串转java.sql.Timestamp
*/
public static Timestamp parseTimestamp(String dateStr) throws Exception {
try {
return new Timestamp(getDateFormater(3).parse(dateStr).getTime());
} catch (ParseException ex) {
throw new Exception("UT-07001:日志字符串" + dateStr + "格式不正确,格式:" + DATEFORMAT[3], ex);
}
}
/**
* 根据指定日期格式,日期字符串转java.sql.Timestamp
*/
public static Timestamp parseTimestamp(String dateStr, int format) throws Exception {
try {
return new Timestamp(getDateFormater(format).parse(dateStr).getTime());
} catch (ParseException ex) {
throw new Exception("UT-07001:日志字符串" + dateStr + "格式不支持", ex);
}
}
// ======================日期计算方法======================================================================================
/**
* 获取两个Calendar日期对象的天数差
*/
public static int calendarMinus(Calendar d1, Calendar d2) {
if (d1 == null || d2 == null) {
return 0;
}
d1.set(11, 0);
d1.set(12, 0);
d1.set(13, 0);
d1.set(14, 0);
d2.set(11, 0);
d2.set(12, 0);
d2.set(13, 0);
d2.set(14, 0);
long t1 = d1.getTimeInMillis();
long t2 = d2.getTimeInMillis();
final long daylong = 86400000L;
t1 -= t1 % daylong;
t2 -= t2 % daylong;
final long t = t1 - t2;
final int value = (int) (t / daylong);
return value;
}
/**
* 获取两个Calendar日期对象的天数差
*/
public static long calendarminus(Calendar d1, Calendar d2) {
if (d1 == null || d2 == null) {
return 0L;
}
return (d1.getTimeInMillis() - d2.getTimeInMillis()) / 86400000L;
}
/**
* 给定任意日期Calendar对象,计算所在月天数
*/
public static int calcMonthDays(Calendar date) {
final Calendar t1 = (Calendar) date.clone();
final Calendar t2 = (Calendar) date.clone();
final int year = date.get(1);
final int month = date.get(2);
t1.set(year, month, 1);
t2.set(year, month + 1, 1);
t2.add(6, -1);
return calendarMinus(t2, t1) + 1;
}
private static int calcDays(long t1, long t2) {
final long millis = t1 - t2;
if (millis == 0) {
return 0;
}
return (int) (millis / (24 * 3600 * 1000));
}
/**
* 获取两个Calendar日期对象的天数差
*/
public static int calcDays(Calendar c1, Calendar c2) {
return calcDays(c1.getTimeInMillis(), c2.getTimeInMillis());
}
/**
* 获取两个java.util.Date日期对象的天数差
*/
public static int calcDays(Date d1, Date d2) {
return calcDays(d1.getTime(), d2.getTime());
}
/**
* 给定任意日期Calendar对象,计算所在月的最后一天
*/
public static Calendar lastDay(Calendar c) {
final Calendar t = (Calendar) c.clone();
t.set(Calendar.DAY_OF_MONTH, 1);
t.add(Calendar.MONTH, 1);
t.add(Calendar.DAY_OF_MONTH, -1);
return t;
}
/**
* 给定任意日期字符串,计算所在月的最后一天
*/
public static Calendar lastDay(String dateStr) throws Exception {
final Calendar t = parseDate(dateStr);
t.set(Calendar.DAY_OF_MONTH, 1);
t.add(Calendar.MONTH, 1);
t.add(Calendar.DAY_OF_MONTH, -1);
return t;
}
/**
* 给定任意日期,计算所在季的季起日期和季终日期
*/
public static Calendar[] calcAQuarter(Calendar day) {
final Calendar[] quarter = new Calendar[2];
int month = 0;
quarter[0] = (Calendar) day.clone();
month = quarter[0].get(Calendar.MONTH);
if (month < 3) {
month = 0;
} else if (month < 6) {
month = 3;
} else if (month < 9) {
month = 6;
} else {
month = 9;
}
quarter[0].set(Calendar.MONTH, month);
quarter[0].set(Calendar.DAY_OF_MONTH, 1);
quarter[1] = (Calendar) quarter[0].clone();
quarter[1].set(Calendar.MONTH, month + 2);
quarter[1] = lastDay(quarter[1]);
return quarter;
}
/**
* 获取年、月、日、时、分、秒、毫秒
*/
public static int[] getYearMonthDayHH24MiMM(Calendar calendar) {
return new int[] {calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND), calendar.get(Calendar.MILLISECOND) };
}
/**
* 获取年、月、日、时、分、秒、毫秒
*/
public static int[] getYearMonthDayHH24MiMM(Date date) {
final Calendar calendar = getSystemCurrentTime();
calendar.setTime(date);
return getYearMonthDayHH24MiMM(calendar);
}
/**
* 好微妙转毫秒
*/
public static long nsToMs(long nsTime) {
return nsTime / 1000000;
}
}
增加航班信息
解决后台传输date数据的日期少一天问题 # serverTimezone=GMT%2B8解决传输date数据时间少一天问题
/**
* 添加航班信息
*
* @param flightEntity
* @return
*/
public int insertFlight(FlightEntity flightEntity) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 1.获取连接
connection = MayiktJdbcUtils.getConnection();
// 开启事务
MayiktJdbcUtils.beginTransaction(connection);
//2.获取执行者对象
preparedStatement = connection.prepareStatement("INSERT INTO `flight`.`mayikt_flight`" +
" (`id`, `flight_id`, `company`, `departure_airport`, `arrive_airport`, `departure_time`, " +
"`arrive_time`, `model`, `is_delete`) VALUES (null, ?, ?,?, ?," +
" ?, ?, ?, " +
"'0');");
preparedStatement.setString(1, flightEntity.getFlightId());
preparedStatement.setString(2, flightEntity.getCompany());
preparedStatement.setString(3, flightEntity.getDepartureAirport());
preparedStatement.setString(4, flightEntity.getArriveAirport());
//date java.sql.date java.util.date
//new Date(flightEntity.getDepartureTime().getTime()) 将java.util.date 转化成 java.sql.date
preparedStatement.setDate(5, new Date(flightEntity.getDepartureTime().getTime()));
preparedStatement.setDate(6, new Date(flightEntity.getArriveTime().getTime()));
preparedStatement.setString(7, flightEntity.getModel());
int result = preparedStatement.executeUpdate();
// 代码执行没有问题的情况下 则直接提交事务
MayiktJdbcUtils.commitTransaction(connection);
return result;
} catch (Exception e) {
e.printStackTrace();
// 回滚事务
MayiktJdbcUtils.rollBackTransaction(connection);
return 0;
} finally {
// 释放资源
MayiktJdbcUtils.closeConnection(preparedStatement, connection);
}
}
@WebServlet("/insertFlight")
public class InsertFlightServlet extends HttpServlet {
private FlightService flightService = new FlightService();
/**
* 跳转到 添加 航班数据页面
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("InsertFlight.jsp").forward(req, resp);
}
/**
* 接受 插入航班数据请求
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String flightId = req.getParameter("flightId");
if (StringUtils.isEmpty(flightId)) {
req.setAttribute("errorMsg", "flightId的值不能够为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
String company = req.getParameter("company");
if (StringUtils.isEmpty(company)) {
req.setAttribute("errorMsg", "company的值不能够为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
String departureAirport = req.getParameter("departureAirport");
if (StringUtils.isEmpty(departureAirport)) {
req.setAttribute("errorMsg", "departureAirport的值不能够为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
String arriveAirport = req.getParameter("arriveAirport");
if (StringUtils.isEmpty(departureAirport)) {
req.setAttribute("errorMsg", "arriveAirport的值不能够为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
// 将日期string类型转化成date
String departureTimeStr = req.getParameter("departureTime");
if (StringUtils.isEmpty(departureTimeStr)) {
req.setAttribute("errorMsg", "departureTime的值不能够为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
Date departureTime = DateUtils.stringToDate(departureTimeStr);
String arriveTimeStr = req.getParameter("arriveTime");
if (StringUtils.isEmpty(departureTimeStr)) {
req.setAttribute("errorMsg", "arriveTime的值不能够为空!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
Date arriveTime = DateUtils.stringToDate(arriveTimeStr);
String model = req.getParameter("model");
FlightEntity flightEntity = new FlightEntity();
flightEntity.setFlightId(flightId);
flightEntity.setDepartureAirport(departureAirport);
flightEntity.setArriveAirport(arriveAirport);
flightEntity.setDepartureTime(departureTime);
flightEntity.setArriveTime(arriveTime);
flightEntity.setModel(model);
flightEntity.setCompany(company);
int result = flightService.insertFlight(flightEntity);
if (result <= 0) {
// 修改失败的情况下
req.setAttribute("errorMsg", "插入失败!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
return;
}
// 如果插入成功的情况下 则重定向到showFlight 查询航班信息
resp.sendRedirect("showFlight");
} catch (Exception e) {
e.printStackTrace();
// 修改失败的情况下
req.setAttribute("errorMsg", "系统错误!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
}
}
}
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>插入航班信息</title>
</head>
<body>
<div>
<h1>插入数据</h1>
<form action="insertFlight" method="post">
<label>航 号: <input type="text"
name="flightId"></label><br>
<label>航空公司: <input type="text" name="company"></label><br>
<label>出发机场: <input type="text" name="departureAirport"></label><br>
<label>达到机场: <input type="text" name="arriveAirport"></label><br>
<label>出发时间: <input type="text" name="departureTime"></label><br>
<label>到达时间: <input type="text" name="arriveTime"></label><br>
<label>机 型: <input type="text"
name="model"></label><br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
逻辑删除航班信息
企业实际开发中 不会真正物理删除数据。
执行deletesql语句 物理将数据进行删除。
企业实际开发中逻辑删除 字段is_delete=0 则显示该行数据is_delete=1 则隐藏
该行数据
逻辑删除本质就是 update is_delete=1----隐藏数据
select where is_delete=0--------显示的数据