【javaWeb+tomcat+MySQL】综合案例-完整步骤

发布于:2022-10-17 ⋅ 阅读:(291) ⋅ 点赞:(0)

一、前提

我的idea版本为:IntelliJ IDEA 2021.1.2 x64

我的apache-tomcat版本为:apache-tomcat-9.0.68

我的apache-tomcat存放路径为:D:\programfiles\apache-tomcat-9.0.68

二、创建一个普通的java项目

File→New Project→命名为myWeb→点击下一步→完成

三、添加Web Application

1、在项目上,鼠标右键Add Framework Suppot

 2、勾选Web Application(4.0),勾选Creat web.xml,点击OK

 3、添加完成后,在项目路径下自动生成web文件夹

四、添加tomcat

1、点击右上方Add Configuration→点击+号→选择Tomcalt Server下的local

2、点击右下角Fix

 

 3、点击Deployment,把下方的Application context命名的后面的单词删掉,保留和项目名一致,我的项目名为myWeb;

五、测试tomcat是否连接成功

在项目目录下,找到index.jsp,在body标签内添加内容hello,点击右上角绿色三角运行

 服务器启动成功,网页自动弹出,效果如下:

 六、在src目录下创建四个package

在src目录下创建四个package,命名如下:(com后面的qingruan为公司名);

之所以要建四个package,是为了分工,不用所有代码凑在一起。

1、com.qingruan.dao:存放方法类StudentDao.java

2、com.qingruan.entity:存放实体类Student.java

3、com.qingruan.test:存放测试类TestDb.java

4、com.qingruan.util:存放连接数据库的类DbUtils.java

七、实体类、方法类、测试类、连接类代码

1、方法类StudentDao.java:

package com.qingruan.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.qingruan.entity.Student;
import com.qingruan.util.DbUtils;

// dao  负责与数据库交互的,目前实现的技术是jdbc
public class StudentDao {
    private static PreparedStatement ps = null;
    private static Connection cn = null;
    private static ResultSet rs =null;

    /**
     * 添加学生
     * @param stu  需要传入的参数是学生对象
     * @return  返回受影响的行数
     */
    public int saveStu(Student stu) { // 传入一个学生对象
        // 1.获得连接
        try {
            cn = DbUtils.getConnection();
            // 2.获得预处理对象
            String sql = "insert into student values(null,?,?,?,?,?,?)";
            ps = cn.prepareStatement(sql);
            // 3.赋予实际的参数
            ps.setString(1, stu.getStu_number());
            ps.setString(2, stu.getStu_name());
            ps.setInt(3, stu.getStu_age());
            ps.setString(4, stu.getStu_sex());
            ps.setInt(5, stu.getStu_score());
            ps.setString(6, stu.getStu_hiredate());
            // 4.得到结果集
            return ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            DbUtils.close(null, ps, cn);// 5.释放资源
        }
        return 0;
    }

    /**
     * 修改学生信息
     * @param stu  需要修改的学生信息
     * @return  返回受影响的行数
     */
    public int updateStu(Student stu){
        try {
            cn = DbUtils.getConnection();
            String sql="update  student set stu_number=?,stu_name=?,stu_age=?,stu_sex=?,stu_score=?,stu_hiredate=? where stu_id=?";
            ps=cn.prepareStatement(sql);
            ps.setString(1, stu.getStu_number());
            ps.setString(2, stu.getStu_name());
            ps.setInt(3, stu.getStu_age());
            ps.setString(4, stu.getStu_sex());
            ps.setInt(5, stu.getStu_score());
            ps.setString(6, stu.getStu_hiredate());
            ps.setInt(7, stu.getStu_id());
            return ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            DbUtils.close(null, ps, cn);
        }
        return 0;
    }

    /**
     * 依据学生id删除学生信息
     * @param stuId  需要删除的学生id
     * @return  返回受影响的行数
     */
    public int delStu(int stuId){
        try {
            cn = DbUtils.getConnection();
            String sql="delete from student where stu_id=?";
            ps=cn.prepareStatement(sql);
            ps.setInt(1, stuId);
            return ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DbUtils.close(null, ps, cn);
        }
        return 0;
    }

    /**
     * 依据学生id查询学生详细信息
     * @param stuId   需要传入的学生编号
     * @return  返回学生都西昂
     */
    public Student  queryByStuId(int stuId){
        Student stu =null;
        try {
            cn = DbUtils.getConnection();
            String sql="select * from student where stu_id=?";
            ps=cn.prepareStatement(sql);
            ps.setInt(1, stuId);
            rs = ps.executeQuery();
            if(rs.next()){
                return stu =new Student(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5), rs.getInt(6), rs.getString("stu_hiredate"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DbUtils.close(rs, ps, cn);
        }
        return stu;
    }

    /**
     * 查询学生列表
     * @return  返回学生集合
     */
    public List<Student>  queryFindAll(){
        List<Student> list =new ArrayList<Student>();
        try {
            cn = DbUtils.getConnection();
            String sql="select * from student";
            ps=cn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                list.add(new Student(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5), rs.getInt(6), rs.getString("stu_hiredate")));//放到集合中
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DbUtils.close(rs, ps, cn);
        }
        return list;
    }

}

2、测试类TestDb.java

package com.qingruan.test;

import java.util.List;

import org.junit.Test;

import com.qingruan.dao.StudentDao;
import com.qingruan.entity.Student;
import com.qingruan.util.DbUtils;

public class TestStuDao {

    StudentDao dao =new StudentDao();

    //保存学生信息
    @Test
    public void save(){
        int result = dao.saveStu(new Student("1013", "江西老表", 22, "男", 95, "2020-9-1"));
        System.out.println(result>0?"添加成功":"添加失败");
    }

    //修改
    @Test
    public void update(){
        Student stu = dao.queryByStuId(17);
        stu.setStu_name("江西老表很哇塞");
        int result = dao.updateStu(stu);
        System.out.println(result>0?"修改成功":"修改失败");
    }

    //删除
    @Test
    public void delete(){
        int result = dao.delStu(17);
        System.out.println(result>0?"删除成功":"删除失败");
    }

    //单个查询
    @Test
    public void findById(){
        Student stu = dao.queryByStuId(16);
        System.out.println(stu);
    }

    //查询所有
    @Test
    public void findAll(){
        List<Student> list = dao.queryFindAll();
        for(Student  stu : list){
            System.out.println(stu);
        }
    }


}

如果@Test是红色异常的,要选中,右键Download Library fom Maven Repository,即可;

3、连接数据库的类DbUtils.java

package com.qingruan.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

// 针对数据库的连接作用
public class DbUtils {

    //定义私有成员
    private static  DataSource ds;

    //1.静态代码块 加载配置文件,初始化连接池对象
    static{     // 特点:用于给类进行初始化,只加载一次,随着类的加载而加载
        try {
            Properties pro =new Properties();
            //加载属性文件
            pro.load(DbUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获得连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    //2.定义一个方法:获取连接对象
    public static Connection getConnection(){
        try {
            return  ds.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //3.定义一个方法:用于释放资源
    public static void close(ResultSet rs,PreparedStatement ps,Connection cn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(cn!=null){
            try {
                cn.close();  //  此时的关闭,是归还给连接池对象
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得连接池的方法
     * @return
     */
    public static  DataSource getDataSource(){
        return ds;
    }

}

4、实体类Student.java

package com.qingruan.entity;

// 学生类 与 数据库中的student学生表是与之对应的
// 将数据库的学生表 看作是 java中的一个学生类   数据库中学生表的字段可以看作是 java中学生类的属性
public class Student {

    private Integer stu_id;  //学生编号(给程序使用)

    private String stu_number;  //学号

    private String stu_name; // 姓名

    private Integer stu_age; // 年龄

    private String stu_sex; // 性别

    private Integer stu_score;//成绩

    private String stu_hiredate; // 入学时间

    public Student() {
        // TODO Auto-generated constructor stub
    }



    public Student(String stu_number, String stu_name, Integer stu_age, String stu_sex, Integer stu_score,
                   String stu_hiredate) {
        this.stu_number = stu_number;
        this.stu_name = stu_name;
        this.stu_age = stu_age;
        this.stu_sex = stu_sex;
        this.stu_score = stu_score;
        this.stu_hiredate = stu_hiredate;
    }


    public Student(Integer stu_id, String stu_number, String stu_name, Integer stu_age, String stu_sex,
                   Integer stu_score, String stu_hiredate) {
        this.stu_id = stu_id;
        this.stu_number = stu_number;
        this.stu_name = stu_name;
        this.stu_age = stu_age;
        this.stu_sex = stu_sex;
        this.stu_score = stu_score;
        this.stu_hiredate = stu_hiredate;
    }



    @Override
    public String toString() {
        return "Student [stu_id=" + stu_id + ", stu_number=" + stu_number + ", stu_name=" + stu_name + ", stu_age="
                + stu_age + ", stu_sex=" + stu_sex + ", stu_score=" + stu_score + ", stu_hiredate=" + stu_hiredate
                + "]";
    }



    public Integer getStu_id() {
        return stu_id;
    }

    public void setStu_id(Integer stu_id) {
        this.stu_id = stu_id;
    }

    public String getStu_number() {
        return stu_number;
    }

    public void setStu_number(String stu_number) {
        this.stu_number = stu_number;
    }

    public String getStu_name() {
        return stu_name;
    }

    public void setStu_name(String stu_name) {
        this.stu_name = stu_name;
    }

    public Integer getStu_age() {
        return stu_age;
    }

    public void setStu_age(Integer stu_age) {
        this.stu_age = stu_age;
    }

    public String getStu_sex() {
        return stu_sex;
    }

    public void setStu_sex(String stu_sex) {
        this.stu_sex = stu_sex;
    }

    public Integer getStu_score() {
        return stu_score;
    }

    public void setStu_score(Integer stu_score) {
        this.stu_score = stu_score;
    }

    public String getStu_hiredate() {
        return stu_hiredate;
    }

    public void setStu_hiredate(String stu_hiredate) {
        this.stu_hiredate = stu_hiredate;
    }







}

八、测试是否成功连接MySQL数据库 

前提:

我的MySQL账号为:root;密码为:1234;

我建的数据库命名为:mydata1

测试java是否成功连接数据库:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestConnectMysql {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1?characterEncoding=utf-8","root","1234");
            System.out.println(cn);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}

连接成功,控制台输出效果如下:

 

九、在web目录下,创建html、css、js文件夹


 
十、在WEB-INF下创建文件夹lib

1、把以下两个包粘贴到lib;(可上网搜)

 2、鼠标右键Add as Library,点击确定,把两个包添加到路径下;

 

十一、把druid.properties粘贴在src目录下

文件druid.properties存放的是数据库的名称、账号和密码。

关于java和MySQL版本和工具,以及相关设置的详细介绍在上一篇,这里不再赘述。

 

十二、Web→WEB-INF→index.jsp后缀改为.html

 内容为:

右上角要选择为Tomcat,再点击绿色三角形,运行;

 

 

运行效果:

javaWeb项目下的.html文件,用tomcat在本地服务器上运行;

 运行以后,要手动关闭,点击右上角红色正方形;

本文含有隐藏内容,请 开通VIP 后查看