信息管理系统---Servlet+javaBean+Druid+DButil

news2024/11/28 10:58:07

这里是学习了Servlet后结合数据库进行增删查改–登录等作为练手项目非常适合

准备工作:

1.数据准备

这张表是用户表,用于登录

CREATE TABLE `users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(25) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `phone` varchar(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

这张表是具体的用户数据

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(25) DEFAULT NULL,
  `name` varchar(10) DEFAULT NULL,
  `gender` varchar(3) DEFAULT NULL,
  `state` varchar(10) DEFAULT NULL,
  `code` varchar(25) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

数据根据需要自行插入

2. 数据库连接

这里是properties文件,需要在resource文件夹下

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/db_test3?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username = root
password = 123456
initialSize=5
minIdle=5
maxActive=10
maxWait=3000

德鲁伊数据库连接

public class DruidUtils {
 private static Properties properties = new Properties();
 private static DruidDataSource dataSource = null;

 static {
     try {
         properties.load(DruidUtils.class.getResourceAsStream("/db.properties"));
          dataSource  = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
          dataSource.setDriverClassName(properties.getProperty("driver"));
          dataSource.setUrl(properties.getProperty("url"));
          dataSource.setUsername(properties.getProperty("username"));
          dataSource.setPassword(properties.getProperty("password"));
     } catch (IOException e) {
         e.printStackTrace();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 public static Connection getConn() {
     try {
         return dataSource.getConnection();
     } catch (SQLException e) {
         e.printStackTrace();
     }
     return null;
 }
//这里是为第三方的DButil建立数据源
 public static DataSource getdataSource(){
     return dataSource;
 }
}

3.登录

userDao

public interface UserDao {

 /**
  * 登录
  * @param aname 账号
  * @param apass 密码
  * @return
  */
 User login(String aname, String apass);
}

Dao层实现类

public class UserDaoImpl implements UserDao {
    private static QueryRunner queryRunner = new QueryRunner(DruidUtils.getdataSource());
    //登录
    @Override
    public User login(String aname, String apass) {
        String sql = "select * from admin_user where aname = ? and apass = ?";
        try {
           return queryRunner.query(sql,new BeanHandler<User>(User.class),aname,apass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Service业务层

public interface UserService {

    User login(String aname, String apass);
}

Service实现类

public class UserServiceImpl implements UserService {
    private static UserDao userDao = new UserDaoImpl();

    @Override
    public User login(String aname, String apass) {
        User user = userDao.login(aname, apass);
        return user;
    }
}

Controller层

package com.fjp.usersys.controller;

import com.fjp.usersys.pojo.User;
import com.fjp.usersys.service.UserService;
import com.fjp.usersys.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    private static UserService userService = new UserServiceImpl();
    private static UsersServlet usersServlet = new UsersServlet();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        login(request, response);
        response.sendRedirect("UsersServlet");
    }
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        String uname = request.getParameter("uname");
        String pass = request.getParameter("pass");

        User user = userService.login(uname, pass);
        request.setAttribute("user", user);
        // 跳转到用户列表页面
        //request.getRequestDispatcher("UsersServlet").forward(request,response);

        //response.getWriter().println("登录成功");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

4.用户信息的增删查改

Dao层及实现类

public interface UsersDao {

    /**
     * 查找全部用户信息
     * @return
     */
    List<Users> findAll();

    /**
     * 通过id查找
     * @param id
     * @return
     */
    Users findById(int id);

    /**
     * 更新
     * @param users
     * @return
     */
    int updateUsers(Users users);

    int deleteUsers(int id);

    int addUser(Users users);
}

public class UsersDaoImpl implements UsersDao {
    private static QueryRunner queryRunner = new QueryRunner(DruidUtils.getdataSource());
    @Override
    public List<Users> findAll() {
        String sql = "select * from user";
        try {
           return queryRunner.query(sql,new BeanListHandler<Users>(Users.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Users findById(int id) {
        String sql = "select * from user where id = ?";
        try {
           return queryRunner.query(sql,new BeanHandler<Users>(Users.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateUsers(Users users) {
        String sql = "update user set username =? , name = ?, gender = ?, state =?, code =? , email =? where id =?";
        try {
          return queryRunner.update(sql ,users.getUsername(),users.getName(),users.getGender(),users.getState(),users.getCode(),users.getEmail(),users.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteUsers(int id) {
        String sql = "delete from user where id =?";
        try {
           return queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int addUser(Users users) {
        String sql = "insert into user values(?,?,?,?,?,?,?)";
        try {
           return queryRunner.update(sql, users.getId(),users.getUsername(),users.getName(),users.getGender(),users.getState(),users.getCode(),users.getEmail());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

Service层及实现类

public interface UsersService {

    /**
     * 查找全部
     * @return
     */
    List<Users> findAll();

    /**
     * id查找
     * @param id
     * @return
     */
    Users findById(int id);
    /**
     * 更新
     * @param users
     * @return
     */
    boolean updateUsers(Users users);

    boolean deleteUsers(int id);

    boolean addUsers(Users users);

}

public class UsersServiceImpl implements UsersService {
    private static UsersDao usersDao = new UsersDaoImpl();
    @Override
    public List<Users> findAll() {
        List<Users> users = usersDao.findAll();
        return users;
    }

    @Override
    public Users findById(int id) {
        Users users = usersDao.findById(id);
        return users;
    }

    @Override
    public boolean updateUsers(Users users) {
        int i = usersDao.updateUsers(users);
        return i>0;
    }

    @Override
    public boolean deleteUsers(int id) {
        int i = usersDao.deleteUsers(id);
        return i>0;
    }

    @Override
    public boolean addUsers(Users users) {
        int i = usersDao.addUser(users);
        return i>0;
    }
}

Controller层

@WebServlet(name = "UsersServlet", value = "/UsersServlet")
public class UsersServlet extends HttpServlet {
    private static UsersService usersService = new UsersServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        if (action == null) {
            findAll(request, response);
        }else if ("findById".equals(action)) {
            findById(request, response);
        }else if("updateUsers".equals(action)){
            updateUsers(request, response);
        }else if ("delete".equals(action)){
            deleteUsers(request, response);
            findAll(request, response);
        }else if ("add".equals(action)) {
            add(request, response);
        }else if ("addUsers".equals(action)){
            addUsers(request, response);
        }

    }

    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Users> users = usersService.findAll();
        PrintWriter writer = response.getWriter();
        writer.print("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>用户管理</title>\n" +
                "</head>\n" +
                "<body>\n" +"<table align='center' width='85%' border='1'>\n" +
                "    <tr>\n" +
                "        <td>编号</td>\n" +
                "        <td>昵称</td>\n" +
                "        <td>姓名</td>\n" +
                "        <td>性别</td>\n" +
                "        <td>状态</td>\n" +
                "        <td>邀请码</td>\n" +
                "        <td>邮箱</td>\n" +
                "<td>操作&nbsp&nbsp&nbsp<a href='UsersServlet?action=add'>新增</a></td>"+
                "    </tr>");
        for (Users user : users) {
            writer.print(" <tr>\n" +
                    "        <td>"+user.getId()+"</td>\n" +
                    "        <td>"+user.getUsername()+"</td>\n" +
                    "        <td>"+user.getName()+"</td>\n" +
                    "        <td>"+user.getGender()+"</td>\n" +
                    "        <td>"+user.getState()+"</td>\n" +
                    "        <td>"+user.getCode()+"</td>\n" +
                    "        <td>"+user.getEmail()+"</td>\n" +
                    "        <td><a href='UsersServlet?id="+user.getId()+"&action=findById'>修改</a>&nbsp&nbsp&nbsp<a href='UsersServlet?id="+user.getId()+"&action=delete'>删除</a></td>\n" +
                    "    </tr>");
        }
        writer.print("</table>\n" +
                "</body>\n" +
                "</html>");
    }
    protected void updateUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //findById(request, response);
        String id = request.getParameter("id");
        int uid = id == null ? 0: Integer.parseInt(id);
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String state = request.getParameter("state");
        String code = request.getParameter("code");
        String email = request.getParameter("email");

        Users users = new Users();
        users.setId(uid);
        users.setUsername(username);
        users.setName(name);
        users.setGender(gender);
        users.setState(state);
        users.setCode(code);
        users.setEmail(email);

        boolean b = usersService.updateUsers(users);
        if (b) {
            response.sendRedirect("UsersServlet");
        }

    }
    protected void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int uid = id== null?0: Integer.parseInt(id);
        Users users = usersService.findById(uid);
        PrintWriter writer = response.getWriter();
        writer.print("<form method=\"post\" action=\"UsersServlet?action=updateUsers\">\n" +
                "        编号:<input type=\"text\" name=\"id\"readonly=\"readonly\" value=\""+users.getId()+"\">\n" +
                "        昵称:<input type=\"text\" name=\"username\" value=\""+users.getUsername()+"\">\n" +
                "        姓名:<input type=\"text\" name=\"name\" value=\""+users.getName()+"\">\n" +
                "        性别:<input type=\"text\" name=\"gender\" value=\""+users.getGender()+"\">\n" +
                "        状态:<input type=\"text\" name=\"state\" value=\""+users.getState()+"\">\n" +
                "        邀请码:<input type=\"text\" name=\"code\" value=\""+users.getCode()+"\">\n" +
                "        邮箱:<input type=\"text\" name=\"email\" value=\""+users.getEmail()+"\">\n" +
                "        <input type=\"submit\" value=\"修改\">\n" +
                "    </form>");
        //updateUsers(request, response);
        //updateUsers(request, response);
    }


    protected void deleteUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int uid = id == null ? 0:Integer.parseInt(id);
        boolean b = usersService.deleteUsers(uid);
    }
    protected void addUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
       int uid = Integer.parseInt(id);
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String state = request.getParameter("state");
        String code = request.getParameter("code");
        String email = request.getParameter("email");
        Users users = new Users();
        users.setId(uid);
        users.setUsername(username);
        users.setName(name);
        users.setGender(gender);
        users.setState(state);
        users.setCode(code);
        users.setEmail(email);
        boolean b = usersService.addUsers(users);
        if (b) {
            response.sendRedirect("UsersServlet");
        }
    }
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Users users = new Users();
        PrintWriter writer = response.getWriter();
        writer.print("<form method=\"post\" action=\"UsersServlet?action=addUsers\">\n" +
                "        编号:<input type=\"text\" name=\"id\" value=\""+users.getId()+"\">\n" +
                "        昵称:<input type=\"text\" name=\"username\" value=\""+users.getUsername()+"\">\n" +
                "        姓名:<input type=\"text\" name=\"name\" value=\""+users.getName()+"\">\n" +
                "        性别:<input type=\"text\" name=\"gender\" value=\""+users.getGender()+"\">\n" +
                "        状态:<input type=\"text\" name=\"state\" value=\""+users.getState()+"\">\n" +
                "        邀请码:<input type=\"text\" name=\"code\" value=\""+users.getCode()+"\">\n" +
                "        邮箱:<input type=\"text\" name=\"email\" value=\""+users.getEmail()+"\">\n" +
                "        <input type=\"submit\" value=\"添加\">\n" +
                "    </form>");
    }
        @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }
}

4.前端

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form action="UserServlet" method="post">
    用户名:<input type="text" name="uname"><br/>
    密码:<input type="password" name="pass"><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

需要的jar包

在这里插入图片描述

代码结构**

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/779890.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++基础(四)】内联函数和auto关键字

&#x1f493;博主CSDN主页:杭电码农-NEO&#x1f493;   ⏩专栏分类:C初阶之路⏪   &#x1f69a;代码仓库:NEO的学习日记&#x1f69a;   &#x1f339;关注我&#x1faf5;带你学习C   &#x1f51d;&#x1f51d; 内联函数 1. 前言2. 内联函数概念3. 内联函数的特性…

数字IC实践项目(7)—CNN加速器的设计和实现(付费项目)

数字IC实践项目&#xff08;7&#xff09;—基于Verilog的CNN加速器&#xff08;付费项目&#xff09; 写在前面的话项目整体框图神经网络框图完整电路框图 项目简介和学习目的软件环境要求 资源占用&板载功耗总结 写在前面的话 项目介绍&#xff1a; 卷积神经网络硬件加速…

基于深度学习的高精度六类海船检测识别系统(PyTorch+Pyside6+YOLOv5模型)

摘要&#xff1a;基于深度学习的高精度六类海船检测识别系统可用于日常生活中检测与定位海船目标&#xff08;散装货船&#xff08;bulk cargo carrier&#xff09;、集装箱船&#xff08;container ship&#xff09;、渔船&#xff08;fishing boat&#xff09;、普通货船&…

[golang gin框架] 41.Gin商城项目-微服务实战之后台Rbac微服务(用户登录 、Gorm数据库配置单独抽离、 Consul配置单独抽离)

上一节抽离了captcha验证码功能,集成了验证码微服务功能,这一节来看看后台Rbac功能,并抽离其中的用户登录,管理员管理,角色管理,权限管理等功能作为微服务来调用 一.引入 后台操作从登录到后台首页,然后其中的管理员管理,角色管理,权限管理等功能可以抽离出来作为 一个Rbac微服…

视频画面尺寸怎么裁剪?裁剪视频画面方法分享

如果我们的视频将在不同的平台或设备上播放&#xff0c;而这些设备具有不同的屏幕比例&#xff08;如16:9、4:3、1:1等&#xff09;&#xff0c;则可能需要裁剪来适应目标屏幕。这样观看起来会体验效果更佳&#xff0c;但是该怎么裁剪视频的画面呢&#xff1f;给大家分享几种裁…

力扣热门100题之最长连续序列【中等】

题目描述 给定一个未排序的整数数组 nums &#xff0c;找出数字连续的最长序列&#xff08;不要求序列元素在原数组中连续&#xff09;的长度。 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 示例 1&#xff1a; 输入&#xff1a;nums [100,4,200,1,3,2] 输出&…

Kotlin多平台最佳架构指南

在这篇文章中&#xff0c;我们将对 Kotlin 多平台移动端的最佳架构进行深入探讨。在2023年&#xff0c;作为 Android 开发者&#xff0c;我们会倾向于采用 MVVM 架构&#xff0c;因为它简单、灵活且易于测试。而作为 iOS 开发者&#xff0c;我们可能会选择 MVC、Viper 等架构。…

解决FLink:Missing required options are: slot.name

[ERROR] Could not execute SQL statement. Reason: org.apache.flink.table.api.ValidationException: One or more required options are missing.Missing required options are:slot.name解决 https://ververica.github.io/flink-cdc-connectors/release-2.4/content/connec…

JSR 规范详解和概述

JSR 规范详解 目录概述需求&#xff1a; 设计思路实现思路分析1.JSR 规范详解 参考资料和推荐阅读 Survive by day and develop by night. talk for import biz , show your perfect code,full busy&#xff0c;skip hardness,make a better result,wait for change,challenge …

Python计算特征值与特征向量案例+传统方法+雅可比Jacobi迭代法

目录 {1}几个例子&#x1f330; {2}特征值 {3}奇异矩阵 {4}特征向量 {5}特征值和特征向量的计算方法 特征值性质 特征向量性质 {6}巩固练习 {7}迭代法 什么时候收敛&#xff1f;收敛速度如何&#xff1f; {8}雅可比迭代法 {1}几个例子&#x1f330; 例1&#xff…

Moshi Vs Gson Vs Kotlin Serialisation性能PK

Moshi Vs Gson Vs Kotlin Serialisation 定义 Gson Gson 是一个Java序列化/反序列化库&#xff0c;用于将Java对象转换为JSON格式&#xff0c;以及将JSON格式转换回Java对象。 Moshi Moshi 是一个现代化的JSON库&#xff0c;适用于Android和Java。它使得将JSON解析为Java对…

Django基本数据库操作

Django基本数据库操作 文章目录 Django基本数据库操作&#x1f468;‍&#x1f3eb;内容一&#xff1a;基本数据库配置&#x1f468;‍&#x1f52c;内容二&#xff1a;ORM基本操作 &#x1f468;‍&#x1f3eb;内容一&#xff1a;基本数据库配置 &#x1f449;Django是一个流…

整车总线系列——FlexRay 四

整车总线系列——FlexRay 四 我是穿拖鞋的汉子&#xff0c;魔都中坚持长期主义的汽车电子工程师。 老规矩&#xff0c;分享一段喜欢的文字&#xff0c;避免自己成为高知识低文化的工程师&#xff1a; 没有人关注你。也无需有人关注你。你必须承认自己的价值&#xff0c;你不能…

机器学习方法与原则

机器学习方法与原则 评价指标 TODO 训练集、验证集与测试集 训练集与测试集 训练集&#xff08;作业&#xff09;&#xff1a; 模型可见样本标签&#xff0c;用于训练模型&#xff0c;样本数量有限。 在训练集上表现好的模型&#xff0c; 在其它未见样本上一定表现好么&am…

【Java】Clonable 接口

如何克隆一个引用所指的对象呢&#xff1f;首先一个前提&#xff0c;他是可克隆的&#xff0c;我们要实现一个Clonable 接口。我们来看一个这个接口&#xff1a; 可以发现里面是空的&#xff0c;我们把这种空接口叫做标记接口&#xff0c;作用就是表示当前对象是可以被克隆的。…

面试 | 双法妙解压缩字符串【遍历统计 + 双指针】

一、题目描述 原题传送门 二、思路分析 首先我们来分析一下解决本题所需要的思路 题目的意思很简单&#xff0c;就是统计原本的字符串中的每个字符出现的次数&#xff0c;然后以【字符&#xff0c;出现的次数】这样的结构来字符串&#xff0c;以起到一个压缩的效果&#xff0c…

Fiddler抓包实战,彻底打通接口测试(二)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 请求查看 Inspec…

Spring简述IOC入门案例

文章目录 Spring学习笔记Spring&#xff1a;Spriing framework:IoC&#xff08;控制反转&#xff09;对象的创建控制权由程序转移到外部&#xff1a;DI( Dependency Injection )依赖注入&#xff1a; IoC入门案例&#xff1a;项目结构&#xff1a;applicationContext.xml:bookD…

mysql-5.7 Linux安装教程

通过命令下载&#xff1a; 下载到 cd /usr/local 这个路径下 wget http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.36-linux-glibc2.12-x86_64.tar.gz 解压&#xff1a; tar -zxvf mysql-5.7.36-linux-glibc2.12-x86_64.tar.gz 将解压的 重命名 为mysql mv mysql-5…

B/S架构的云HIS系统源码 技术架构:Angular+Nginx+ Java+Spring

基于云计算技术的B/S架构的HIS系统源码&#xff0c;为基层医疗机构提供标准化的、信息化的、可共享的医疗信息管理系统&#xff0c;实现医患事务管理和临床诊疗管理等标准医疗管理信息系统的功能。系统利用云计算平台的技术优势&#xff0c;建立统一的健康档案存储平台&#xf…