赞
踩
用Servlset + JSP + JDBC 实现增删改查
先看看结构
entity是一个学生类,repository是一个与数据库交互的类,servlet与用户交互
关于idea里面连接数据库遇到的时区问题
好了进入正题
先看一下效果
准备一个学生类(展示少量代码)
- 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" %>
- <html>
- <head>
- <title>$Title$</title>
- </head>
- <body>
- <h1>学生管理系统</h1>
- <table>
- <tr>
- <th>编号</th>
- <th>姓名</th>
- </tr>
- <c:forEach items="${list}" var="student">
- <tr>
- <td>${student.id}</td>
- <td>${student.username}</td>
- <td><a href="/student?method=deleteBId&id=${student.id}">删除</a></td>
- <td><a href="/student?method=findBId&id=${student.id}">修改</a></td>
- </tr>
- </c:forEach>
- </table>
- <h3><td><a href="add.jsp">添加</a></td></h3>
- </body>
- </html>
这是添加页面add.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <form action="/student" method="post">
- 编号<input type="text" name="id"><br/>
- 姓名<input type="text" name="username">
- <input type="hidden" name="method" value="add">
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
这是修改操作
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <form action="/student" method="post">
- 编号<input type="text" name="id" value="${student.id}"><br>
- 姓名<input type="text" name="username">
- <input type="hidden" name="method" value="update">
- <input type="submit" value="修改">
- </form>
- </body>
- </html>
注意隐藏标签,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<Student> 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<Student> list = new ArrayList<>();
- /**
- * 查询
- * @return
- */
- public List<Student> 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);
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。