servlet实现管理系统的增删查

本文档详细介绍了如何使用servlet进行用户管理系统的增、删、查操作。首先,在项目中创建必要的文件和目录,接着在UserDaoImpl中定义接口,并在UserServiceImpl中实现接口方法。然后,创建AddServlet、DeleteServlet、FindServlet三个servlet类,分别处理添加、删除和查询请求。在web.xml配置文件中添加相应配置,并更新jsp文件,包括新增addUser.jsp用于用户添加,修改allUser.jsp展示所有用户信息。
摘要由CSDN通过智能技术生成

先在项目中创建这些文件夹和文件
在这里插入图片描述

在这里插入图片描述

在上次servlet的基础上
在UserDaoImpl中输入:

package com.zhongruan.dao.impl;

import com.zhongruan.DBUtil.DBUtil;
import com.zhongruan.dao.IUserDao;
import com.zhongruan.model.User;

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

public class UserDaoImpl implements IUserDao {

    @Override
    public User findUserByUsername(String username) {
        Connection connection=null;
        User user=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection= DBUtil.getConnection();
            String sql="select * from tb_user where username=?";
            statement=connection.prepareStatement(sql);
            statement.setString(1,username);
            resultSet=statement.executeQuery();
            while (resultSet.next()){
                 user=new User();
                 user.setId(resultSet.getInt(1));
                user.setUsername(username);
                user.setPassword(resultSet.getString(3));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeALL(resultSet,statement,connection);
        }
        return user;
    }


    @Override
    public List<User> findAll() {
        List<User> users=new ArrayList<>();
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
             connection= DBUtil.getConnection();
             String sql="select * from tb_user";
            statement=connection.prepareStatement(sql);
            resultSet=statement.executeQuery();
            while (resultSet.next()){
                User user=new User();
                user.setId(resultSet.getInt(1));
                user.setUsername(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                users.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeALL(resultSet,statement,connection);
        }
        return users;
    }

    @Override
    public void delete(int id) {
        Connection connection=null;
        PreparedStatement statement=null;
        try {
            connection=DBUtil.getConnection();
            statement=connection.prepareStatement("delete from tb_user where id=?");
             statement.setInt(1,id);
              statement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeALL(null,statement,connection);
        }
    }

    @Override
    public void add(String username, String password) {
        Connection connection=null;
        PreparedStatement statement=null;
        try {
            connection=DBUtil.getConnection();
            statement=connection.prepareStatement("insert into tb_user(username,password) value (?,?)");
            statement.setString(1,username);
            statement.setString(2,password);
            statement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeALL(null,statement,connection);
        }
    }
}

并在其下设置接口

package com.zhongruan.dao;


import com.zhongruan.model.User;

import java.util.List;


public interface IUserDao {
    User findUserByUsername(String username);
    List<User> findAll();
    void delete(int id);
    void add(String username,String password);
    }

在UserServiceImpl中添加一些新的代码

package com.zhongruan.service.Impl;

import com.zhongruan.dao.IUserDao;
import com.zhongruan.model.User;
import com.zhongruan.dao.impl.UserDaoImpl;
import com.zhongruan.service.IUserService;

import java.util.List;

public class UserServiceImpl implements IUserService {
    IUserDao userDao = new UserDaoImpl();
    @Override
    public Boolean login(String username, String password) {
        User user = userDao.findUserByUsername(username);
        if (user!= null && user.getPassword().equals(password)) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<User> findAll() {
        List<User> users = userDao.findAll();
        return users;
    }

    @Override
    public void delete(int id) {
      userDao.delete(id);
    }

    @Override
    public void add(String username, String password) {
        userDao.add(username,password);
    }
}

并设置接口

package com.zhongruan.service.Impl;

import com.zhongruan.dao.IUserDao;
import com.zhongruan.model.User;
import com.zhongruan.dao.impl.UserDaoImpl;
import com.zhongruan.service.IUserService;

import java.util.List;

public class UserServiceImpl implements IUserService {
    IUserDao userDao = new UserDaoImpl();
    @Override
    public Boolean login(String username, String password) {
        User user = userDao.findUserByUsername(username);
        if (user!= null && user.getPassword().equals(password)) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<User> findAll() {
        List<User> users = userDao.findAll();
        return users;
    }

    @Override
    public void delete(int id) {
      userDao.delete(id);
    }

    @Override
    public void add(String username, String password) {
        userDao.add(username,password);
    }
}

新增AddServlet、DeleteServlet、FindServlet文件

在AddServlet中输入

package com.zhongruan.servlet;

import com.zhongruan.service.IUserService;
import com.zhongruan.service.Impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        IUserService userService = new UserServiceImpl();
        userService.add(username, password);
        request.getRequestDispatcher("/find").forward(request,response);
    }
}

在DeleteServlet中输入

package com.zhongruan.servlet;

import com.zhongruan.service.IUserService;
import com.zhongruan.service.Impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id1=request.getParameter("id");
        int id2=Integer.parseInt(id1);
        IUserService userService=new UserServiceImpl();
        userService.delete(id2);
        request.getRequestDispatcher("/find").forward(request,response);
    }
}

在FindServlet输入

package com.zhongruan.servlet;

import com.zhongruan.model.User;
import com.zhongruan.service.IUserService;
import com.zhongruan.service.Impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class FindServlet extends HttpServlet {
    IUserService userService=new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users=userService.findAll();
        HttpSession session=request.getSession();
        session.setAttribute("userlist",users);
        request.getRequestDispatcher("allUser.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users=userService.findAll();
        HttpSession session=request.getSession();
        session.setAttribute("userlist",users);
        request.getRequestDispatcher("allUser.jsp").forward(request,response);
    }
}


在web.xml新增一些代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.zhongruan.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>DeleteServlet</servlet-name>
        <servlet-class>com.zhongruan.servlet.DeleteServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DeleteServlet</servlet-name>
        <url-pattern>/delete</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>FindServlet</servlet-name>
        <servlet-class>com.zhongruan.servlet.FindServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FindServlet</servlet-name>
        <url-pattern>/find</url-pattern>
    </servlet-mapping>
    
    <servlet>
    <servlet-name>AddServlet</servlet-name>
    <servlet-class>com.zhongruan.servlet.AddServlet</servlet-class>
</servlet>
    <servlet-mapping>
        <servlet-name>AddServlet</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>UpdataServlet</servlet-name>
        <servlet-class>com.zhongruan.servlet.AddServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UpdataServlet</servlet-name>
        <url-pattern>/updata</url-pattern>
    </servlet-mapping>
</web-app>

新增addUser.jsp文件 修改allUser.jsp文件
addUser.jsp:

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

<html>
<head>
    <title>新增用户</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于servlet+jsp框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增用户</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="/add"
              method="post">
        <%--用&nbsp;&nbsp;户&nbsp;&nbsp;id:<input type="text" name="id"><br><br><br>br--%>
        用户姓名:<input type="text" name="username"><br><br><br>
        用户密码:<input type="text" name="password"><br><br><br>
        <input type="submit" value="添加" >
    </form>

</div>

allUser.jsp:

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

<html>
<head>
    <title>user列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于servlet+jsp框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>用户列表 —— 显示所有用户</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="addUser.jsp">新增</a>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>id</th>
                    <th>用户名</th>
                    <th>密码</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="user" items="${userlist}">
               <tr>
                    <tr>
                   <td>${user.id}</td>
                   <td>${user.username}</td>
                    <td>${user.password}</td>
                    <td>
                        <a href="/delete?id=${user.id}">删除</a>
                        <a href="/updata?id=${user.id}">|修改</a>
                    </td>
                </tr>
               </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值