Java Servlet+jsp实现一个航班系统

采用MVC框架设计,tomcat版本:8.5.61,mysql版本:8.0.13

如果你想直接copy,项目地址奉上:zljr/flight: 一个使用servlet+jsp写的航班系统 (github.com)icon-default.png?t=N7T8https://github.com/zljr/flight

项目结构:

首先在根目录创建libs文件夹,加入需要用的jar包:

并右键libs,点击Add as llibrary.

再创建FlightEntity实体类:

package cn.edu.zuel.entity;

import java.util.Date;

public class FlightEntity {
    /*id
    * */
    private Integer id;
    /*
    * 航班号*/
    private String flightId;
    /*
    * 航空公司*/
    private String company;
    /*
    * 出发机场*/
    private String departureAirport;
    /*
    * 到达机场*/
    private String arriveAirport;
    /*
    * 出发时间*/
    private Date departureTime;
    /*
    * 到达时间*/
    private Date arriveTime;
    /*
    * 机型*/
    private String model;
    /*
    * 是否隐藏  0:显示  1:隐藏*/
    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 FlightEntity() {
    }

    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;
    }
}

再在src目录下创建config.properties配置文件,配置数据库连接的信息

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/flight?serverTimezone=UTC
user=填自己的用户名
password=填自己的密码

再创建工具类,JdbcUtil工具类:

package cn.edu.zuel.utils;
import java.io.*;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;
    static {
        try{
            InputStream resourceAsStream =JdbcUtil.class.getClassLoader().getResourceAsStream("config.properties");
            Properties properties=new Properties();
            properties.load(resourceAsStream);
            driverClass=properties.getProperty("driverClass");
            url=properties.getProperty("url");
            user= properties.getProperty("user");
            password=properties.getProperty("password");
            Class.forName(driverClass);

        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public static Connection getConnection(){//建立连接
        try{
            return DriverManager.getConnection(url,user,password);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection){//关闭查询连接
        try{
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void closeConnection(Statement statement, Connection connection){//关闭修改数据连接
        closeConnection(null,statement,connection);
    }
    public static void beginTransaction(Connection connection){//开始事务
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void endTransaction(Connection connection){//结束事务
        try{
            connection.setAutoCommit(true);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void rollbackTransaction(Connection connection){//回滚事务
        try{
            if(connection!=null){
                connection.rollback();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
    public static  void commit(Connection connection){//提交事务
        try{
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

再创建DateUtils工具类:

package cn.edu.zuel.utils;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;

public class DateUtils {

    /**
     * 仅显示年月日,例如 2015-08-11.
     */
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    /**
     * 显示年月日时分秒,例如 2015-08-11 09:51:53.
     */
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 仅显示时分秒,例如 09:51:53.
     */
    public static final String TIME_FORMAT = "HH:mm:ss";

    /**
     * 每天的毫秒数 8640000.
     */
    public static final long MILLISECONDS_PER_DAY = 86400000L;

    /**
     * 每周的天数.
     */
    public static final long DAYS_PER_WEEK = 7L;

    /**
     * 每小时毫秒数.
     */
    public static final long MILLISECONDS_PER_HOUR = 3600000L;

    /**
     * 每分钟秒数.
     */
    public static final long SECONDS_PER_MINUTE = 60L;

    /**
     * 每小时秒数.
     */
    public static final long SECONDS_PER_HOUR = 3600L;

    /**
     * 每天秒数.
     */
    public static final long SECONDS_PER_DAY = 86400L;

    /**
     * 每个月秒数,默认每月30天.
     */
    public static final long SECONDS_PER_MONTH = 2592000L;

    /**
     * 每年秒数,默认每年365天.
     */
    public static final long SECONDS_PER_YEAR = 31536000L;

    /**
     * 常用的时间格式.
     */
    private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
            "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };

    /**
     * 得到当前日期字符串.
     * @return String 日期字符串,例如2015-08-11
     * @since 1.0
     */
    public static String getDate() {
        return getDate(DateUtils.DATE_FORMAT);
    }

    /**
     * 得到当前时间字符串.
     * @return String 时间字符串,例如 09:51:53
     * @since 1.0
     */
    public static String getTime() {
        return formatDate(new Date(), DateUtils.TIME_FORMAT);
    }

    /**
     * 得到当前日期和时间字符串.
     * @return String 日期和时间字符串,例如 2015-08-11 09:51:53
     * @since 1.0
     */
    public static String getDateTime() {
        return formatDate(new Date(), DateUtils.DATETIME_FORMAT);
    }

    /**
     * 获取当前时间指定格式下的字符串.
     * @param pattern
     *            转化后时间展示的格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
     * @return String 格式转换之后的时间字符串.
     * @since 1.0
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * 获取指定日期的字符串格式.
     * @param date  需要格式化的时间,不能为空
     * @param pattern 时间格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
     * @return String 格式转换之后的时间字符串.
     * @since 1.0
     */
    public static String getDate(Date date, String pattern) {
        return DateFormatUtils.format(date, pattern);
    }

    /**
     * 获取日期时间字符串,默认格式为(yyyy-MM-dd).
     * @param date 需要转化的日期时间
     * @param pattern 时间格式,例如"yyyy-MM-dd" "HH:mm:ss" "E"等
     * @return String 格式转换后的时间字符串
     * @since 1.0
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, DateUtils.DATE_FORMAT);
        }
        return formatDate;
    }

    /**
     * 获取当前年份字符串.
     * @return String 当前年份字符串,例如 2015
     * @since 1.0
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 获取当前月份字符串.
     * @return String 当前月份字符串,例如 08
     * @since 1.0
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 获取当前天数字符串.
     * @return String 当前天数字符串,例如 11
     * @since 1.0
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * 获取当前星期字符串.
     * @return String 当前星期字符串,例如星期二
     * @since 1.0
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    /**
     * 将日期型字符串转换为日期格式.
     * 支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
     * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
     * @param str
     * @return Date
     * @since 1.0
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取当前日期与指定日期相隔的天数.
     * @param date 给定的日期
     * @return long 日期间隔天数,正数表示给定日期在当前日期之前,负数表示在当前日期之后
     * @since 1.0
     */
    public static long pastDays(Date date) {
        // 将指定日期转换为yyyy-MM-dd格式
        date = DateUtils.parseDate(DateUtils.formatDate(date, DateUtils.DATE_FORMAT));
        // 当前日期转换为yyyy-MM-dd格式
        Date currentDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
        long t=0;
        if(date!=null&&currentDate!=null){
            t = (currentDate.getTime() - date.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
        }
        return t;
    }

    /**
     * 获取当前日期指定天数之后的日期.
     * @param num   相隔天数
     * @return Date 日期
     * @since 1.0
     */
    public static Date nextDay(int num) {
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num);
        return curr.getTime();
    }

    /**
     * 获取当前日期指定月数之后的日期.
     * @param num   间隔月数
     * @return Date 日期
     * @since 1.0
     */
    public static Date nextMonth(int num) {
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + num);
        return curr.getTime();
    }

    /**
     * 获取当前日期指定年数之后的日期.
     * @param num    间隔年数
     * @return Date 日期
     * @since 1.0
     */
    public static Date nextYear(int num) {
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + num);
        return curr.getTime();
    }

    /**
     * 将 Date 日期转化为 Calendar 类型日期.
     * @param date   给定的时间,若为null,则默认为当前时间
     * @return Calendar Calendar对象
     * @since 1.0
     */
    public static Calendar getCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        // calendar.setFirstDayOfWeek(Calendar.SUNDAY);//每周从周日开始
        // calendar.setMinimalDaysInFirstWeek(1); // 设置每周最少为1天
        if (date != null) {
            calendar.setTime(date);
        }
        return calendar;
    }

    /**
     * 计算两个日期之间相差天数.
     * @param start     计算开始日期
     * @param end       计算结束日期
     * @return long 相隔天数
     * @since 1.0
     */
    public static long getDaysBetween(Date start, Date end) {
        // 将指定日期转换为yyyy-MM-dd格式
        start = DateUtils.parseDate(DateUtils.formatDate(start, DateUtils.DATE_FORMAT));
        // 当前日期转换为yyyy-MM-dd格式
        end = DateUtils.parseDate(DateUtils.formatDate(end, DateUtils.DATE_FORMAT));

        long diff=0;
        if(start!=null&&end!=null) {
            diff = (end.getTime() - start.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
        }
        return diff;
    }

    /**
     * 计算两个日期之前相隔多少周.
     * @param start      计算开始时间
     * @param end    计算结束时间
     * @return long 相隔周数,向下取整
     * @since 1.0
     */
    public static long getWeeksBetween(Date start, Date end) {
        return getDaysBetween(start, end) / DateUtils.DAYS_PER_WEEK;
    }

    /**
     * 获取与指定日期间隔给定天数的日期.
     * @param specifiedDay    给定的字符串格式日期,支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss",
     *            "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss",
     *            "yyyy/MM/dd HH:mm"
     * @param num   间隔天数
     * @return String 间隔指定天数之后的日期
     * @since 1.0
     */
    public static String getSpecifiedDayAfter(String specifiedDay, int num) {
        Date specifiedDate = parseDate(specifiedDay);
        Calendar c = Calendar.getInstance();
        c.setTime(specifiedDate);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + num);
        String dayAfter = formatDate(c.getTime(), DateUtils.DATE_FORMAT);
        return dayAfter;
    }

    /**
     * 计算两个日期之前间隔的小时数.
     *
     * @param date1
     *            结束时间
     * @param date2
     *            开始时间
     * @return String 相差的小时数,保留一位小数
     * @since 1.0
     */
    public static String dateMinus(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return "0";
        }
        Long r = date1.getTime() - date2.getTime();
        DecimalFormat df = new DecimalFormat("#.0");
        double result = r * 1.0 / DateUtils.MILLISECONDS_PER_HOUR;
        return df.format(result);
    }

    /**
     * 获取当前季度 .
     *
     * @return Integer 当前季度数
     * @since 1.0
     */
    public static Integer getCurrentSeason() {
        Calendar calendar = Calendar.getInstance();
        Integer month = calendar.get(Calendar.MONTH) + 1;
        int season = 0;
        if (month >= 1 && month <= 3) {
            season = 1;
        } else if (month >= 4 && month <= 6) {
            season = 2;
        } else if (month >= 7 && month <= 9) {
            season = 3;
        } else if (month >= 10 && month <= 12) {
            season = 4;
        }
        return season;
    }

    /**
     * 将以秒为单位的时间转换为其他单位.
     *
     * @param seconds
     *            秒数
     * @return String 例如 16分钟前、2小时前、3天前、4月前、5年前等
     * @since 1.0
     */
    public static String getIntervalBySeconds(long seconds) {
        StringBuffer buffer = new StringBuffer();
        if (seconds < SECONDS_PER_MINUTE) {
            buffer.append(seconds).append("秒前");
        } else if (seconds < SECONDS_PER_HOUR) {
            buffer.append(seconds / SECONDS_PER_MINUTE).append("分钟前");
        } else if (seconds < SECONDS_PER_DAY) {
            buffer.append(seconds / SECONDS_PER_HOUR).append("小时前");
        } else if (seconds < SECONDS_PER_MONTH) {
            buffer.append(seconds / SECONDS_PER_DAY).append("天前");
        } else if (seconds < SECONDS_PER_YEAR) {
            buffer.append(seconds / SECONDS_PER_MONTH).append("月前");
        } else {
            buffer.append(seconds / DateUtils.SECONDS_PER_YEAR).append("年前");
        }
        return buffer.toString();
    }

    /**
     *
     * getNowTimeBefore(记录时间相当于目前多久之前)
     *
     * @param seconds
     *            秒
     * @return
     * @exception @since
     *                1.0
     * @author rlliu
     */
    public static String getNowTimeBefore(long seconds) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("上传于");
        if (seconds < 3600) {
            buffer.append((long) Math.floor(seconds / 60.0)).append("分钟前");
        } else if (seconds < 86400) {
            buffer.append((long) Math.floor(seconds / 3600.0)).append("小时前");
        } else if (seconds < 604800) {
            buffer.append((long) Math.floor(seconds / 86400.0)).append("天前");
        } else if (seconds < 2592000) {
            buffer.append((long) Math.floor(seconds / 604800.0)).append("周前");
        } else if (seconds < 31104000) {
            buffer.append((long) Math.floor(seconds / 2592000.0)).append("月前");
        } else {
            buffer.append((long) Math.floor(seconds / 31104000.0)).append("年前");
        }
        return buffer.toString();
    }

    /**
     *
     * getMonthsBetween(查询两个日期相隔的月份)
     *
     * @param startDate 开始日期1 (格式yyyy-MM-dd)
     * @param endDate   截止日期2 (格式yyyy-MM-dd)
     * @return
     */
    public static int getMonthsBetween(String startDate, String endDate) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(DateUtils.parseDate(startDate));
        c2.setTime(DateUtils.parseDate(endDate));
        int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
        int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        return Math.abs(year * 12 + month);
    }

    /**
     *
     * getDayOfWeek(获取当前日期是星期几)
     *
     * @param dateStr 日期
     * @return 星期几
     */
    public static String getDayOfWeek(String dateStr) {
        String[] weekOfDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Date date = parseDate(dateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int num = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        return weekOfDays[num];
    }

    /**
     * sns 格式 如几秒前,几分钟前,几小时前,几天前,几个月前,几年后, ... 精细,类如某个明星几秒钟之前发表了一篇微博
     *
     * @param createTime
     * @return
     */
    public static String snsFormat(long createTime) {
        long now = System.currentTimeMillis() / 1000;
        long differ = now - createTime / 1000;
        String dateStr = "";
        if (differ <= 60) {
            dateStr = "刚刚";
        } else if (differ <= 3600) {
            dateStr = (differ / 60) + "分钟前";
        } else if (differ <= 3600 * 24) {
            dateStr = (differ / 3600) + "小时前";
        } else if (differ <= 3600 * 24 * 30) {
            dateStr = (differ / (3600 * 24)) + "天前";
        } else {
            Date date = new Date(createTime);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            dateStr = sdf.format(date);
        }
        return dateStr;
    }

    /**
     * 得到UTC时间,类型为字符串,格式为"yyyy-MM-dd HH:mm"
     * 如果获取失败,返回null
     * @return
     */
    public static String getUTCTimeStr() {
        StringBuffer UTCTimeBuffer = new StringBuffer();
        // 1、取得本地时间:
        Calendar cal = Calendar.getInstance() ;
        // 2、取得时间偏移量:
        int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
        // 3、取得夏令时差:
        int dstOffset = cal.get(Calendar.DST_OFFSET);
        // 4、从本地时间里扣除这些差量,即可以取得UTC时间:
        cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        UTCTimeBuffer.append(year).append("-").append(month).append("-").append(day) ;
        UTCTimeBuffer.append(" ").append(hour).append(":").append(minute) ;
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            sdf.parse(UTCTimeBuffer.toString()) ;
            return UTCTimeBuffer.toString() ;
        }catch(ParseException e)
        {
            e.printStackTrace() ;
        }
        return null ;
    }
}

再创建FlightDao类(用于数据库增删改查)

package cn.edu.zuel.dao;

import cn.edu.zuel.entity.FlightEntity;
import cn.edu.zuel.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
//import java.util.Date;
import java.sql.Date;
public class FlightDao {
    public ArrayList<FlightEntity> allFlight(){//查询所有航班信息
        Connection conn=null;
        PreparedStatement stat=null;
        ResultSet resultSet=null;
        try{
            conn=JdbcUtil.getConnection();

            String selectSql="select *from flight where is_delete=0";
            stat=conn.prepareStatement(selectSql);//使用预编译参数防止sql注入
            resultSet=stat.executeQuery();
            ArrayList<FlightEntity> arrayList=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");
               arrayList.add(new FlightEntity(id,flightId,company,departureAirport,arriveAirport,departureTime,arriveTime,model,isDelete));
            }
            return arrayList;
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }finally{

            JdbcUtil.closeConnection(resultSet,stat,conn);
        }
    }
    public int delFlight(Integer id){//删除航班信息
        Connection conn=null;
        PreparedStatement stat=null;
        try{
            conn=JdbcUtil.getConnection();
            JdbcUtil.beginTransaction(conn);
            String delSql="delete from flight where id=?";
            stat=conn.prepareStatement(delSql);
            stat.setInt(1,id);
            int i = stat.executeUpdate();
            JdbcUtil.commit(conn);
            return i;
        }catch (Exception e){
            e.printStackTrace();
            JdbcUtil.rollbackTransaction(conn);
            return 0;
        }finally {
            JdbcUtil.closeConnection(stat,conn);
        }
    }
    public FlightEntity queryById(Integer id){//根据id查询航班信息
        Connection conn=null;
        PreparedStatement stat=null;
        ResultSet resultSet=null;
        try{
            conn=JdbcUtil.getConnection();
            String querySql="select *from flight where id=?";
            stat=conn.prepareStatement(querySql);
            stat.setInt(1,id);
            resultSet=stat.executeQuery();
            if(resultSet.next()){
                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);
                return flightEntity;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            JdbcUtil.closeConnection(resultSet,stat,conn);
        }
    }
    public int updateFlight(FlightEntity flightEntity){//更新航班信息
        Connection conn=null;
        PreparedStatement stat=null;
        try{
            conn=JdbcUtil.getConnection();
            JdbcUtil.beginTransaction(conn);//涉及到修改数据,需要使用事务
            String updateSql="update flight set flight_id=?,company=?,departure_airport=?,arrive_Airport=?,departure_time=?," +
                    "arrive_time=?,model=?,is_delete=0 where id=?";
            stat=conn.prepareStatement(updateSql);
            stat.setString(1, flightEntity.getFlightId());
            stat.setString(2, flightEntity.getCompany());
            stat.setString(3, flightEntity.getDepartureAirport());
            stat.setString(4, flightEntity.getArriveAirport());
            /*
            * 将java.util.Date转换为java.sql.Date*/
            stat.setDate(5,new Date(flightEntity.getDepartureTime().getTime()+ 8 * 60 * 60 * 1000));//加8小时才是北京时间
            stat.setDate(6,new Date(flightEntity.getArriveTime().getTime()+ 8 * 60 * 60 * 1000));
            stat.setString(7, flightEntity.getModel());
            stat.setInt(8,flightEntity.getId());
            int result=stat.executeUpdate();
            JdbcUtil.commit(conn);
            if(result!=0){
                return result;
            }else{
                return 0;
            }
        }catch (Exception e){
            e.printStackTrace();
            JdbcUtil.rollbackTransaction(conn);
            return 0;
        }finally {
            JdbcUtil.closeConnection(stat,conn);
        }
    }
    public int insertFlight(FlightEntity flightEntity){//插入航班信息
        Connection conn=null;
        PreparedStatement stat=null;
        try{
            conn=JdbcUtil.getConnection();
            JdbcUtil.beginTransaction(conn);
            String insertSql="insert into flight values(null,?,?,?,?,?,?,?,0)";
            stat=conn.prepareStatement(insertSql);
            stat.setString(1,flightEntity.getFlightId());
            stat.setString(2,flightEntity.getCompany());
            stat.setString(3,flightEntity.getDepartureAirport());
            stat.setString(4, flightEntity.getArriveAirport());
            stat.setDate(5,new Date(flightEntity.getDepartureTime().getTime()+ 8 * 60 * 60 * 1000));
            stat.setDate(6,new Date(flightEntity.getArriveTime().getTime()+ 8 * 60 * 60 * 1000));
            stat.setString(7,flightEntity.getModel());
//            stat.setInt(8,flightEntity.getIsDelete());
            int result = stat.executeUpdate();
            JdbcUtil.commit(conn);
            if(result>0){
                return result;
            }
            return 0;
        }catch (Exception e){
            e.printStackTrace();
            JdbcUtil.rollbackTransaction(conn);
            return 0;
        }finally {
            JdbcUtil.closeConnection(stat,conn);
        }
    }
    public int updateDelete(Integer id){//逻辑删除
        Connection conn=null;
        PreparedStatement stat=null;
        try{
            conn=JdbcUtil.getConnection();
            JdbcUtil.beginTransaction(conn);//涉及到修改数据,需要使用事务
            String updateSql="update flight set is_delete=? where id=?";
            stat=conn.prepareStatement(updateSql);
            stat.setInt(1, 1);
            stat.setInt(2, id);

            int result=stat.executeUpdate();
            JdbcUtil.commit(conn);
            if(result!=0){
                return result;
            }else{
                return 0;
            }
        }catch (Exception e){
            e.printStackTrace();
            JdbcUtil.rollbackTransaction(conn);
            return 0;
        }finally {
            JdbcUtil.closeConnection(stat,conn);
        }
    }
}

再创建FlightService类,封装FlightDao:

package cn.edu.zuel.service;

import cn.edu.zuel.dao.FlightDao;
import cn.edu.zuel.entity.FlightEntity;


import java.util.ArrayList;

public class FlightService {
    private FlightDao flightDao=new FlightDao();
    public ArrayList<FlightEntity> allFlight(){
        return flightDao.allFlight();
    }
    public int delFlight(Integer id){return flightDao.delFlight(id);}
    public FlightEntity queryById(Integer id){return flightDao.queryById(id);}
    public int updateFlight(FlightEntity flightEntity){return flightDao.updateFlight(flightEntity);}
    public int insertFlight(FlightEntity flightEntity){return flightDao.insertFlight(flightEntity);}
    public int updateDelete(Integer id){return flightDao.updateDelete(id);}
}

再创建Sevlet。

FlightServlet类:
package cn.edu.zuel.servlet;

import cn.edu.zuel.entity.FlightEntity;
import cn.edu.zuel.service.FlightService;

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 java.io.IOException;
import java.util.ArrayList;

@WebServlet("/showAllFlight")
public class FlightServlet extends HttpServlet {
    private FlightService flightService=new FlightService();
    @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<FlightEntity> arrayList =flightService.allFlight();
            req.setAttribute("allFlight",arrayList);
            req.getRequestDispatcher("flight.jsp").forward(req,resp);
    }
}
UpdateFlightServlet类:
package cn.edu.zuel.servlet;

import cn.edu.zuel.entity.FlightEntity;
import cn.edu.zuel.service.FlightService;
import cn.edu.zuel.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;


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 java.io.IOException;
import java.util.Date;

@WebServlet("/updateFlight")
public class UpdateFlightServlet extends HttpServlet {
    private FlightService flightService=new FlightService();
    /*
    * doGet回显:用户点击删除这条数据需要先查询到这条数据*/
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String idStr = req.getParameter("id");
        if(idStr==null||idStr==""){
            req.setAttribute("errorMsg","id的值为空!");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        try{
            Integer id=Integer.parseInt(idStr);
            FlightEntity flightEntity = flightService.queryById(id);
            if(flightEntity==null){
                req.setAttribute("errorMsg","找不到该条航班信息");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
                return;
            }
            req.setAttribute("oneFlight",flightEntity);
            req.getRequestDispatcher("update.jsp").forward(req,resp);

        }catch (NumberFormatException e){
            e.printStackTrace();
            req.setAttribute("errorMsg","数据格式转换失败!");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("errorMsg","系统错误!");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//这里很重要,一定要设置,不然会乱码,导致数据库里的表的数据也乱码
        resp.setContentType("text/html;charset=utf-8");
        String idStr = req.getParameter("id");
        if(StringUtils.isEmpty(idStr)){
            req.setAttribute("errorMsg","id为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        Integer id=Integer.parseInt(idStr);//转为Integer类型
        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(arriveAirport)){
            req.setAttribute("errorMsg","arriveAirport为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
//        这里就要转化格式
        String departureTimeStr = req.getParameter("departureTime");
        if(StringUtils.isEmpty(departureTimeStr)){
            req.setAttribute("errorMsg","departureTime为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        Date departureTime = DateUtils.parseDate(departureTimeStr);
        String arriveTimeStr = req.getParameter("arriveTime");
        if(StringUtils.isEmpty(arriveTimeStr)){
            req.setAttribute("errorMsg","arriveTime为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        Date arriveTime = DateUtils.parseDate(arriveTimeStr);
        String model = req.getParameter("model");
        if(StringUtils.isEmpty(model)){
            req.setAttribute("errorMsg","model为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        FlightEntity flightEntity = new FlightEntity();
        flightEntity.setId(id);
        flightEntity.setFlightId(flightId);
        flightEntity.setCompany(company);
        flightEntity.setDepartureAirport(departureAirport);
        flightEntity.setArriveAirport(arriveAirport);
        flightEntity.setDepartureTime(departureTime);
        flightEntity.setArriveTime(arriveTime);
        flightEntity.setModel(model);
        int result = flightService.updateFlight(flightEntity);
        if(result<=0){
            req.setAttribute("errorMsg","系统异常");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        resp.sendRedirect("showAllFlight");

    }
}
InsertFlightServlet类:
package cn.edu.zuel.servlet;

import cn.edu.zuel.entity.FlightEntity;
import cn.edu.zuel.service.FlightService;
import cn.edu.zuel.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;

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 java.io.IOException;
import java.util.Date;

@WebServlet("/insertFlight")
public class InsertFlightServlet extends HttpServlet {
    private FlightService flightService=new FlightService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.getRequestDispatcher("insert.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
//        String idStr=req.getParameter("id");
//        if(idStr==""||idStr==null){
//            req.setAttribute("errorMsg","id不能为空");
//            req.getRequestDispatcher("error.jsp");
//        }
//        Integer id=Integer.parseInt(idStr);//转为Integer类型
        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(arriveAirport)){
            req.setAttribute("errorMsg","arriveAirport为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
//        这里就要转化格式
        String departureTimeStr = req.getParameter("departureTime");
        if(StringUtils.isEmpty(departureTimeStr)){
            req.setAttribute("errorMsg","departureTime为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        Date departureTime = DateUtils.parseDate(departureTimeStr);
        String arriveTimeStr = req.getParameter("arriveTime");
        if(StringUtils.isEmpty(arriveTimeStr)){
            req.setAttribute("errorMsg","arriveTime为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        Date arriveTime = DateUtils.parseDate(arriveTimeStr);
        String model = req.getParameter("model");
        if(StringUtils.isEmpty(model)){
            req.setAttribute("errorMsg","model为空");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        FlightEntity flightEntity = new FlightEntity();
//        flightEntity.setId(id);
        flightEntity.setFlightId(flightId);
        flightEntity.setCompany(company);
        flightEntity.setDepartureAirport(departureAirport);
        flightEntity.setArriveAirport(arriveAirport);
        flightEntity.setDepartureTime(departureTime);
        flightEntity.setArriveTime(arriveTime);
        flightEntity.setModel(model);
        int result = flightService.insertFlight(flightEntity);
        if(result<=0){
            req.setAttribute("errorMsg","系统异常");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        resp.sendRedirect("showAllFlight");
    }
}
DeleteFlightServlet类:
package cn.edu.zuel.servlet;

import cn.edu.zuel.service.FlightService;

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 java.io.IOException;

@WebServlet("/delFlight")
public class DeleteFlightServlet extends HttpServlet {
    private FlightService flightService=new FlightService();
    @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 {
        String idStr=req.getParameter("id");//传过来的是String类型
        if(idStr==null||idStr==""){
//            跳转到错误页面
            req.setAttribute("errorMsg","id的值为空!");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        }
        try{
            Integer id=Integer.parseInt(idStr);//强转成Integer类型
            int result = flightService.updateDelete(id);
            if(result>0){//删除成功,跳转至航班展示页面(重定向)
                resp.sendRedirect("showAllFlight");
            }else{
                req.setAttribute("errorMsg","很遗憾,删除失败!");
                req.getRequestDispatcher("error.jsp").forward(req,resp);
            }
        }catch (NumberFormatException e){
            e.printStackTrace();
            req.setAttribute("errorMsg","类型转换异常");
            req.getRequestDispatcher("error.jsp").forward(req,resp);

        }catch (Exception e){
            req.setAttribute("errorMsg","系统异常");
            req.getRequestDispatcher("error.jsp").forward(req,resp);

        }

    }
}

再来创建各个jsp:

index.jsp(默认给出,修改代码即可):

<%--
  Created by IntelliJ IDEA.
  User: 浙李鞠人
  Date: 2024/4/20
  Time: 20:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="/flight_war_exploded/showAllFlight">点击进入航班系统</a>
</body>
</html>

flight.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 浙李鞠人
  Date: 2024/4/20
  Time: 20:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>航班系统</title>
</head>
<body>
<table border="1" align="center" style="border-collapse: collapse;width:80%">
  <tr>
    <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="${allFlight}" var="flight">
    <tr align="center">
            <td align="center">${flight.flightId}</td>
            <td align="center">${flight.company}</td>
            <td align="center">${flight.departureAirport}</td>
            <td align="center">${flight.arriveAirport}</td>
            <td align="center">${flight.departureTime}</td>
            <td align="center">${flight.arriveTime}</td>
            <td align="center">${flight.model}</td>
            <td align="center"><a href="/flight_war_exploded/updateFlight?id=${flight.id}">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/flight_war_exploded/delFlight?id=${flight.id}">删除</a></td>
    </tr>
        </c:forEach>


</table>
<a href="/flight_war_exploded/insertFlight">新增航班信息</a>
</body>
</html>

insert.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 浙李鞠人
  Date: 2024/4/30
  Time: 22:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>插入航班信息</title>
</head>
<body>
<div>
    <h1>新增数据</h1>
    <form action="insertFlight" method="post">
        <%--        设置一个隐藏域,不给用户看,给后端传递参数--%>
        <input type="hidden" name="id">
        <label>航&nbsp;&nbsp;&nbsp;&nbsp;号:<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>机&nbsp;&nbsp;&nbsp;&nbsp;型:<input type="text" name="model"></label><br>
        <input type="submit" value="提交">
    </form>
</div>
</body>
</html>

error.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 浙李鞠人
  Date: 2024/4/20
  Time: 21:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>发生了错误,错误的原因是:${errorMsg}</h1>
</body>
</html>

update.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 浙李鞠人
  Date: 2024/4/21
  Time: 0:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>修改航班信息</title>
</head>
<body>
<div>
<h1>修改数据</h1>
    <form action="updateFlight" method="post">
<%--        设置一个隐藏域,不给用户看,给后端传递参数--%>
        <input type="hidden" value="${oneFlight.id}" name="id">
        <label>航&nbsp;&nbsp;&nbsp;&nbsp;号:<input type="text" value="${oneFlight.flightId}" name="flightId"></label><br>
        <label>航空公司:<input type="text" value="${oneFlight.company}" name="company"></label><br>
        <label>出发机场:<input type="text" value="${oneFlight.departureAirport}" name="departureAirport"></label><br>
        <label>抵达机场:<input type="text" value="${oneFlight.arriveAirport}" name="arriveAirport"></label><br>
        <label>出发时间:<input type="text" value="${oneFlight.departureTime}" name="departureTime"></label><br>
        <label>抵达时间:<input type="text" value="${oneFlight.arriveTime}" name="arriveTime"></label><br>
        <label>机&nbsp;&nbsp;&nbsp;&nbsp;型:<input type="text" value="${oneFlight.model}" name="model"></label><br>
        <input type="submit" value="提交">
    </form>
</div>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值