击穿JDBC 例子详解 JDBC+Servlet +jsp增删改查案例(三)全

用Servlset + JSP + JDBC 实现增删改查

 

先看看结构

entity是一个学生类,repository是一个与数据库交互的类,servlet与用户交互

击穿JDBC 例子详解 JDBC+Servlet +jsp增删改查案例(三)全_第1张图片

击穿JDBC 例子详解 JDBC+Servlet +jsp增删改查案例(三)全_第2张图片

击穿JDBC 例子详解 JDBC+Servlet +jsp增删改查案例(三)全_第3张图片

关于idea里面连接数据库遇到的时区问题

击穿JDBC 例子详解 JDBC+Servlet +jsp增删改查案例(三)全_第4张图片

好了进入正题


先看一下效果

击穿JDBC 例子详解 JDBC+Servlet +jsp增删改查案例(三)全_第5张图片

 准备一个学生类(展示少量代码)

public class Student {
    private Integer id;
    private String username;

    public Student(Integer id, String username) {
        this.id = id;
        this.username = username;
    }

 准备一个工具类DBUtil用来快捷处理数据库连接

public class DBUtil {
    //静态方法更方便
    static Connection connection;
    static String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    static String user = "root";
    static String password = "123456";

    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void close(ResultSet resultSet, Statement statement,Connection connection){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 这是主页面,用到了forech标签

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

  
    $Title$
  
  
    

学生管理系统

编号 姓名
${student.id} ${student.username} 删除 修改

添加

 这是添加页面add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    
编号
姓名

这是修改操作

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    
编号
姓名

 注意隐藏标签,form表单method都设置是post请求,那么怎么区分呢add和update呢,设置隐藏标签,这样就能区分了

主要要看StudentServlet类,根据这个类去回看jsp,因为他接收jsp传过来的method再去调用数据库操作

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    StudentRepository studentRepository = new StudentRepository();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method){
            case "add":
                req.setCharacterEncoding("UTF-8");
                String idStr = req.getParameter("id");
                String username = req.getParameter("username");
                Integer id = Integer.parseInt(idStr);
                studentRepository.add(id,username);
                break;
            case "update":
                String idStr1 = req.getParameter("id");
                String username1 = req.getParameter("username");
                Integer id1 = Integer.parseInt(idStr1);
                studentRepository.update(id1,username1);
                resp.sendRedirect("/student");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method == null) {
            method = "findAll";
        }
        switch (method){
            case "findAll":
                studentRepository = new StudentRepository();
                List list = studentRepository.findAll();
                req.setAttribute("list",list);
                req.getRequestDispatcher("index.jsp").forward(req,resp);
                break;
            case "deleteBId":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                studentRepository.delete(id);
                resp.sendRedirect("/student");
                break;
            case "findBId":
                String idStr1 = req.getParameter("id");
                Integer id1 = Integer.parseInt(idStr1);
                Student student = studentRepository.find(id1);
                req.setAttribute("student",student);
                req.getRequestDispatcher("update.jsp").forward(req,resp);
                break;
        }
    }
}

 findBId 是在index.jsp里面点击修改,把id参数传了过来,调用find方法把查询结果放在student里,再转到update.jsp,这样编号对应的才是我们要修改的

repository类

public class StudentRepository {
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    Connection connection = null;
    Student student = null;
    List list = new ArrayList<>();
    /**
     * 查询
     * @return
     */
    public List findAll() {
        try {
            Connection connection = DBUtil.getConnection();
            String sql = "select * from t_user";
            //取得数据库操作对象
            preparedStatement = connection.prepareStatement(sql);

            resultSet = preparedStatement.executeQuery(sql);
            //依次取出
            while (resultSet.next()) {
                Integer id = resultSet.getInt(1);
                String username = resultSet.getString(2);
                student = new Student(id,username);
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            DBUtil.close(resultSet,preparedStatement,connection);
        }
        return list;
    }

    /**
     * 添加
     * @param id
     * @param username
     */
    public void add(Integer id, String username){
        try {
            connection = DBUtil.getConnection();
            String sql = "insert into t_user(id,username) values (?,?)";
            //取得数据库操作对象
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            preparedStatement.setString(2,username);
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭流
             DBUtil.close(resultSet,preparedStatement,connection);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Integer id){
        try{
            connection = DBUtil.getConnection();
            String sql = "delete from t_user where id = ?";
            //取得数据库操作对象
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(resultSet,preparedStatement,connection);
        }
    }

    /**
     * 将需要修改的信息传给student对象
     * @param id
     */
    public Student find(Integer id){
        Student student = null;
        try{
            connection = DBUtil.getConnection();
            String sql = "select * from t_user where id = ?";
            //取得数据库操作对象
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            resultSet = preparedStatement.executeQuery();
            //一个结果不用遍历
            Integer id1 = resultSet.getInt(1);
            String username1 = resultSet.getString(2);
            student = new Student(id1,username1);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(resultSet,preparedStatement,connection);
        }
        return student;
    }

    /**
     * 修改
     */
    public void update(Integer id, String username){
        try{
            connection = DBUtil.getConnection();
            String sql = "update t_user set username=? where id=?";
            //取得数据库操作对象
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setInt(2,id);
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(resultSet,preparedStatement,connection);
        }
    }
}

你可能感兴趣的:(Java,web,java)