首先,为了更好地规范代码,可以分别将不同用处的Java文件放置到不同的文件夹里面

对于实体类,可以放在名为Bean的package里面

对于中间用来实现Java与jsp页面交互的类,可以放在名为Servlet的package里面

对于放置增删改查操作的方法的类,可以放在名为Dao的package里面

对于如果你不想要每次每一个操作方法就要连接一次数据库的话,可以将连接数据库的方法放在DBUtil.java类里面,放在名为DBUtils的package里面

具体的实现方法如下:

//userBean.java
public class userBean{
private String name;
private String id;
private String teacher;
private String whe;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setId(String id){
this.id=id;
}
public String getId(){
return id;
}
public void setTeacher(String teacher){
this.teacher=teacher;
}
public String getTeacher(){
return teacher;
}
public void setWhe(String whe){
this.whe=whe;
}
public String getWhe(){
return whe;
}
public userBean(){}
public userBean(String name,String id,String teacher,String whe){
this.name=name;
this.id=id;
this.teacher=teacher;
this.whe=whe;
}

封装数据库的连接操作时,可以选择使用JDBC连接,也可以使用db.properties进行连接,在这里示范的是后者

//db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:/mysql://localhost:3306/数据库名称?
username=root
password=pass

需要注意到的是,有时db文件里面的url需要加上时区等内容,否则就会报错!

//DBUtil.java
package DBUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String pass;

    static{
        InputStream is=DBUtil.class.getClassLoader().getResourceAsStream("db.resources");

        Properties p=new Properties();
        try{
            p.load(is);
            driver=p.getProperty("driver");
            url=p.getProperty("url");
            username=p.getProperty("username");
            pass=p.getProperty("pass");

            Class.forName(driver);
            System.out.println("驱动注册成功!");

        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConn() throws SQLException {
        Connection conn=null;
        conn= DriverManager.getConnection(url,username,pass);
        System.out.println("数据库连接成功!");
        return conn;
    }

    public static void close(PreparedStatement ps,Connection conn) throws SQLException {
        if(ps!=null){
            ps.close();
        }
        if(conn!=null){
            conn.close();
        }
    }

    public static void close(Statement stmt,Connection conn) throws SQLException {
        if(stmt!=null){
            stmt.close();
        }
        if(conn!=null){
            conn.close();
        }
    }

    public static void close(PreparedStatement ps,Connection conn,ResultSet rs) throws SQLException {
        if(rs!=null){
            rs.close();
        }
        if(ps!=null){
            ps.close();
        }
        if(conn!=null){
            conn.close();
        }
    }
}
//interDao.java
package Dao;

import Bean.mainBean;

import java.sql.SQLException;
import java.util.List;

public interface interDao {
    boolean addMain(mainBean bean) throws SQLException;

    List<mainBean> searchMain(String name) throws SQLException;

    boolean updateMain(mainBean main) throws SQLException;

    boolean deleteMain(String name) throws SQLException;
}

//getDao.java
package Dao;

import Bean.mainBean;
import DBUtils.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class getDao implements interDao{

    private static final String sql_insert="insert into we values(?,?,?,?)";
    private static final String sql_delete="delete from we where name=?";
    private static final String sql_update="update we set id=?,teacher=?,whe=? where name=?";
    private static final String sql_search="select * from we where name=?";

    @Override
    public boolean addMain(mainBean main) throws SQLException {

        Connection conn= null;
        PreparedStatement ps=null;
        try {
            conn = DBUtil.getConn();
            ps=conn.prepareStatement(sql_insert);
            ps.setString(1,main.getName());
            ps.setString(2,main.getId());
            ps.setString(3,main.getTeacher());
            ps.setString(4,main.getWhe());

            int x=ps.executeUpdate();

            return x>0?true:false;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn);
        }

    }

    @Override
    public List<mainBean> searchMain(String name) throws SQLException {
        List<mainBean> list=new ArrayList<mainBean>();
        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            ps=conn.prepareStatement(sql_search);
            ps.setString(1,name);
            rs=ps.executeQuery();
            while(rs.next()){
                mainBean main=new mainBean();
                main.setName(rs.getString("name"));
                main.setId(rs.getString(1));
                main.setTeacher(rs.getString(2));
                main.setWhe(rs.getString(3));

                list.add(main);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn,rs);
        }
        return null;
    }

    @Override
    public boolean updateMain(mainBean main) throws SQLException {
        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        try{
            ps=conn.prepareStatement(sql_update);
            ps.setString(1,main.getName());
            ps.setString(2,main.getId());
            ps.setString(3,main.getTeacher());
            ps.setString(4,main.getWhe());

            int x=ps.executeUpdate();
            return x>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn);
        }
    }

    @Override
    public boolean deleteMain(String name) throws SQLException {
        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        try{
            ps=conn.prepareStatement(sql_delete);
            ps.setString(1,name);

            int x=ps.executeUpdate();
            return x>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn);
        }
    }
}

//mainServlet.java
package Servlet;

import Bean.mainBean;
import Dao.getDao;

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.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/mainServlet")
public class mainServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    getDao gg=new getDao();

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.setCharacterEncoding("utf-8");

             String method=req.getParameter("method");

             try {
                 if ("searchMain".equals(method)) {
                     searchMain(req, resp);
                 } else if ("addMain".equals(method)) {
                     addMain(req, resp);
                 } else if ("updateMain".equals(method)) {
                     updateMain(req, resp);
                 } else if ("deleteMain".equals(method)) {
                     deleteMain(req, resp);
                 }
             } catch (SQLException e) {
                 e.printStackTrace();
             }
    }

    public mainServlet(){ super(); }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        doGet(req, resp);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at:").append(req.getContextPath());
    }

    private void searchMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");

        List<mainBean> list=gg.searchMain(name);

        req.setAttribute("list",list);
        req.getRequestDispatcher("search.jsp").forward(req,resp);

    }

    private void addMain(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");
        String id=req.getParameter("id");
        String teacher=req.getParameter("teacher");
        String whe=req.getParameter("whe");

        mainBean main=new mainBean();
        main.setName(name);
        main.setId(id);
        main.setTeacher(teacher);
        main.setWhe(whe);

        if(gg.addMain(main)){
            req.setAttribute("main",main);
            req.setAttribute("name","添加成功!");
            req.getRequestDispatcher("search.jsp").forward(req,resp);
        }else{
            req.setAttribute("name","添加失败!");
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
    }

    protected void updateMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");
        String id=req.getParameter("id");
        String teacher=req.getParameter("teacher");
        String whe=req.getParameter("whe");

        mainBean main=new mainBean();
        main.setName(name);
        main.setId(id);
        main.setTeacher(teacher);
        main.setWhe(whe);

        if(gg.updateMain(main)){
            req.setAttribute("main","修改成功!");
            req.getRequestDispatcher("search.jsp").forward(req,resp);
        }else{
            req.setAttribute("main","修改失败!");
            req.getRequestDispatcher("update.jsp").forward(req,resp);
        }

    }

    protected void deleteMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");

        if(gg.deleteMain(name)){
            req.setAttribute("name","删除成功!");
            req.getRequestDispatcher("search.jsp").forward(req,resp);
        }else{
            req.setAttribute("name","删除失败!");
            req.getRequestDispatcher("delete.jsp").forward(req,resp);
        }
    }
}

//Main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主界面</title>
</head>
<body>
<center>
    <tr>
        <button type="submit" value="添加" onclick="window.location.href='index.jsp'">添加信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="修改" onclick="window.location.href='update.jsp'">修改信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="删除" onclick="window.location.href='delete.jsp'">删除信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="浏览" onclick="window.location.href='search.jsp'">浏览信息</button>
    </tr>
</center>
</body>
</html>
//index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>添加界面</title>
  </head>
  <body>
  <center>
    <form action="mainServlet?method=addMain" method="post">
      <table>
        <tr>
          <td>学生姓名:</td>
          <td><input type="text" name="name" id="name" placeholder="请输入学生姓名" required></td>
        </tr>
        <p>
        <tr>
          <td>学生学号:</td>
          <td><input type="text" name="id" id="id" placeholder="请输入学生学号:" required></td>
        </tr>
        <p>
        <tr>
          <td>教师姓名:</td>
          <td><input type="text" name="teacher" id="teacher" placeholder="请输入教师姓名:" required></td>
        </tr>
        <p>
        <tr>
          <td>授课地点:</td>
          <td><input type="text" name="whe" id="whe" placeholder="请输入授课地点:" required></td>
        </tr>
        <p>
      </table>
      <tr>
        <button type="submit" value="提交">提交</button>
      </tr>
    </form>
  </center>
  </body>
</html>
//search.jsp
<%@ page import="DBUtils.DBUtil" %>
<%@ page import="java.sql.*" %><%--
  Created by IntelliJ IDEA.
  User: 12140
  Date: 2022/10/18
  Time: 17:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>浏览界面</title>
</head>
<body>
<center>
    <tr>
        <th scope="col">学生姓名</th>
        <th scope="col">学生学号</th>
        <th scope="col">教师姓名</th>
        <th scope="col">授课地点</th>
    </tr>
    <%
        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/ad?useUnicode=true&characterEncoding=utf-8","root","20214063");
        Statement ps=conn.createStatement();
        ResultSet rs=ps.executeQuery("select * from we");

        while(rs.next()){
            out.println("<tr><th scope=row >"+rs.getString(1)+"</th><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td></tr>");
        }
        rs.close();
        ps.close();
        conn.close();
    %>
</center>
</body>
</html>
//update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改界面</title>
</head>
<body>
<center>
    <form action="mainServlet?method=update" method="post">
        <table>
            <h1>修改界面</h1>
            <tr>
                <td>学生姓名:</td>
                <td><input type="text" placeholder="请输入你想要修改的学生姓名"></td>
            </tr>
            <p>
            <tr>
                <td>学生学号:</td>
                <td><input type="text" placeholder="学生学号"></td>
            </tr>
            <p>
            <tr>
                <td>教师姓名:</td>
                <td><input type="text" placeholder="教师姓名"></td>
            </tr>
            <p>
            <tr>
                <td>授课地点:</td>
                <td><input type="text" placeholder="授课地点"></td>
            </tr>
        </table>
        <p>
        <button type="submit" value="提交">修改</button>
    </form>
</center>
</body>
</html>
//delete.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>删除界面</title>
</head>
<body>
<center>
  <form action="mainServlet?method=deleteMain" method="post">
      <table>
          <h1>删除</h1>
          <tr>
              <td>学校姓名:</td>
              <td><input type="text" name="name" id="name" placeholder="请输入你想要删除的学生姓名:"></td>
          </tr>
      </table>
      <p>
      <button type="submit" value="提交">删除</button>
  </form>
</center>
</body>
</html>

本次内容仅仅提供代码进行参考,对界面是否漂亮并没有做出要求!!!

原文地址:http://www.cnblogs.com/liuzijin/p/16797959.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性