十四、jsp(淘汰)
1、jsp的概述
1.什么是JSP=Java Server Pages java服务器端页面
2.程序员在开发过程中,发现Servlet做界面非常不方便,所以产生了jsp技术,JSP其实是对Servlet进行了包装而已。
3.为什么会出现JSP(Java Server Pages)技术?
jsp + java类(service、javabean)+ servlet,就会构成mvc的开发模式,mvc模式是目前软件公司中相当通用的开发模式。
jsp底层是基于Servlet封装。
mvc架构模式
jsp 可以编写java代码
jsp转化成 servlet
index.jsp—-底层变成 index.java(servlet)—–class index.class
2、jsp的原理
1.jsp运行在服务器
2.jsp的基础是Servlet(相当于对Servlet进行了一个包装而已)
3.jsp就是根据: html + java片段 + JSP标签(语法) + javascript(css)
3、jsp的特点
1.JSP的全称是Java Server Pages,它和Servlet技术一样,都是SUN公司定义的一种用于开发动态web资源的技术。
2.jsp这门技术的最大的特点在于,写jsp就像在写HTML,但:它相对于html而言,html只能为用户提供静态数据,而jsp技术允许在页面中嵌套java代码,为用户提供动态数据。
3.相比Servlet而言,Servlet很难对数据进行排版,而jsp除了可以用java代码产生动态数据的同时,也很容易对数据进行排版。
4、jsp的入门
<%@ 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();
}
}
5、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>
6、el表达式
Expression Language表达式语言,用于简化JSP页面内的Java代码
主要功能:获取数据
语法:${expression}
例:${users}获取域中存储的key为users的数据
1. page:当前页面有效
2. request:当前请求有效
3. session:当前会话有效
4. application:当前应用有效
7、jstl标签
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 |
环境步骤:
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;
}
}
导入jar包
文档:javaweb开发相关资料下载.note
链接:有道云笔记
jsp 中定义c标签
<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core_rt” %>
MVC架构模式
十五、jsp+servlet+jdbc开发航班系统
1、需求分析数据准备
需求分析
数据准备
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
工具类
package com.mayikt.utils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
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();
}
}
}
}
MVC架构模式
MVC是一个架构模式,它强制性的使应用程序的输入、处理和输出分开。使用MVC应用程序被分成三个核心部件:模型、视图、控制器。他们各自处理自己的任务。
1.视图
视图是用户看到并与之交互的界面 jsp
2.模型
模型表示企业数据(数据模型:dao)和业务规划及操作(业务模型:service)
3.控制器
控制器表示用户的输入并调用模型和视图去完成用户的需求。
常见的MVC组件:Struts,Spring MVC,JSF
MVC架构模式
- 视图层
- 控制层
- 业务逻辑层
- 数据库访问层
2、查询所有航班信息
实体类
package com.mayikt.entity;import java.util.Date;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; }}
数据库访问层
package com.mayikt.dao;import com.mayikt.entity.FlightEntity;import com.mayikt.utils.MayiktJdbcUtils;import java.sql.Connection;import java.sql.Date;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;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(); }}
控制层
package com.mayikt.servlet;import com.mayikt.entity.FlightEntity;import com.mayikt.service.FlightService;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.util.List;@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>
3、修改航班信息
数据回显
<!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);
}
package com.mayikt.servlet;
import com.mayikt.entity.FlightEntity;
import com.mayikt.service.FlightService;
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;
@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>
修改数据
工具类
package com.mayikt.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
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;
}
}
4、增加航班信息
解决后台传输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);
}
}
package com.mayikt.servlet;
import com.mayikt.entity.FlightEntity;
import com.mayikt.service.FlightService;
import com.mayikt.utils.DateUtils;
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 org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.Date;
@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>
5、逻辑删除航班信息
企业实际开发中 不会真正物理删除数据。
执行deletesql语句 物理将数据进行删除。
企业实际开发中逻辑删除 字段is_delete=0 则显示该行数据is_delete=1 则隐藏
该行数据
逻辑删除本质就是 update is_delete=1—-隐藏数据
select where is_delete=0——–显示的数据
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/81326.html