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

这里是学习了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包

在这里插入图片描述

代码结构**

在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

gazebo simulation

<?xml version"1.0" ?> <!-- --> <!-- | This document was autogenerated by xacro from /home/xrh/ros-project/gazebo_test/src/fmauch_universal_robot/ur_description/urdf/ur3_D455_2f140.urdf.xacro | --> <!-- | EDITING THIS…

C# Yolo+Onnx 号牌识别

参考 https://github.com/missxingwu/net_yolov5_plate https://github.com/ivilson/Yolov7net https://github.com/we0091234/Chinese_license_plate_detection_recognition 效果 项目 VS2022.net 4.8OpenCvSharp4Microsoft.ML.OnnxRuntime 部分代码 using System; using …

基于RASC的keil电子时钟制作(瑞萨RA)(3)----使用J-Link烧写程序到瑞萨芯片

基于RASC的keil电子时钟制作3_使用J-Link烧写程序到瑞萨芯片 概述硬件准备视频教程软件准备hex文件准备J-Link与瑞萨开发板进行SWD方式接线烧录 概述 这一节主要讲解如何使用J-Link对瑞萨RA芯片进行烧录。 硬件准备 首先需要准备一个开发板&#xff0c;这里我准备的是芯片型…

【内网自制无需密码的SSL证书--适用与IP或者localhost】

内网自制无需密码的SSL证书--适用与IP或者localhost 前言步骤确认是否安装openssl自制CA私钥自制csr文件免除密码自制CA证书 验证 前言 搞半死&#xff0c;原来这么简单&#xff0c;今天就把教程分享给大家&#xff0c;本文基于CentOS7环境的openssl生成SSL自制证书&#xff0…

Jmeter+Jenkins+Ant自动化持续集成环境搭建

一、安装准备 1.JDK:jdk-8u121-windows-x64 2.jmeter工具&#xff1a;apache-jmeter-2.13 3.ANT工具&#xff1a;apache-ant-1.9.7-bin 4.jenkins工具&#xff1a;jenkins-2.32.2 二、软件安装 1.JDK的安装 >双击JDK安装包&#xff0c;选择安装路径&#xff08;本人是…

7.12 redis未授权访问漏洞

在1.txt添加存在redis未授权访问漏洞的IP redis.py输入脚本 redis-cli exe -h IP -p 端口号

基于MATLAB的无人机遥感数据预处理与农林植被性状估算实践

遥感技术作为一种空间大数据手段&#xff0c;能够从多时、多维、多地等角度&#xff0c;获取大量的农情数据。数据具有面状、实时、非接触、无伤检测等显著优势&#xff0c;是智慧农业必须采用的重要技术之一。本内容主要针对农业、林业、生态、遥感背景的对无人机遥感有兴趣的…

操作系统笔记、面试八股(三)—— 系统调用与内存管理

文章目录 3. 系统调用3.1 用户态与内核态3.2 系统调用分类3.3 如何从用户态切换到内核态&#xff08;系统调用举例&#xff09; 4. 内存管理4.1 内存管理是做什么的4.1.1 为什么需要虚拟地址空间4.1.2 使用虚拟地址访问内存有什么优势 4.2 常见的内存管理机制4.3 分页管理4.3.1…

OpenCV4图像处理-图像交互式分割-GrabCut

本文将实现一个与人&#xff08;鼠标&#xff09;交互从而分割背景的程序。 GrabCut 1.理论介绍2. 鼠标交互3. GrabCut 1.理论介绍 用户指定前景的大体区域&#xff0c;剩下为背景区域&#xff0c;还可以明确指出某些地方为前景或者背景&#xff0c;GrabCut算法采用分段迭代的…

2.多线程-初阶(中)

文章目录 4. 多线程带来的的风险-线程安全 (重点)4.1 观察线程不安全4.2 线程安全的概念4.3 线程不安全的原因4.3.1原子性4.3.2可见性4.3.3代码顺序性 4.4 解决之前的线程不安全问题 5. synchronized[ˈsɪŋkrənaɪzd] 关键字-监视器锁monitor lock5.1 synchronized 的特性5.…

数据分享|R语言逻辑回归、Naive Bayes贝叶斯、决策树、随机森林算法预测心脏病...

全文链接&#xff1a;http://tecdat.cn/?p23061 这个数据集&#xff08;查看文末了解数据免费获取方式&#xff09;可以追溯到1988年&#xff0c;由四个数据库组成。克利夫兰、匈牙利、瑞士和长滩。"目标 "字段是指病人是否有心脏病。它的数值为整数&#xff0c;0无…

ElasticSearch学习--数据聚合

介绍 数据聚合可以帮助我们对海量的数据进行统计分析&#xff0c;如果结合kibana&#xff0c;我们还能形成可视化的图形报表。自动补全可以根据用户输入的部分关键字去自动补全和提示。数据同步可以帮助我们解决es和mysql的数据一致性问题。集群可以帮助我们了解结构和不同节点…

Flask 文件上传,删除上传的文件

目录结构 app.py from flask import Flask, request, render_template, redirect, url_for import osapp Flask(__name__) BASE_DIR os.getcwd() UPLOAD_FOLDER os.path.join(BASE_DIR, testfile)app.route(/) def home():files os.listdir(UPLOAD_FOLDER)return render_t…

回归预测 | MATLAB实现TCN-BiGRU时间卷积双向门控循环单元多输入单输出回归预测

回归预测 | MATLAB实现TCN-BiGRU时间卷积双向门控循环单元多输入单输出回归预测 目录 回归预测 | MATLAB实现TCN-BiGRU时间卷积双向门控循环单元多输入单输出回归预测预测效果基本介绍模型描述程序设计参考资料 预测效果 ![6 基本介绍 1.MATLAB实现TCN-BiGRU时间卷积双向门控循…

解决JMeter+Grafana+influxdb 配置出现transaction无数据情形

问题描述 JMeterGrafanainfluxdb 配置时&#xff0c;Darren洋发现jmeter中明明已经配置好了事务条件以及接口实例信息&#xff0c;但就是在grafana的头部导航栏中的transaction按钮下来没有相应事务数据信息&#xff0c;经过相关资料查询&#xff0c;Darren洋发现执行以下两个步…

前端,测试,后端,该如何选择?

前端开发&#xff0c;测试&#xff0c;后端&#xff0c;该如何选择&#xff1f;说实话&#xff0c;只要对互联网行业有了解的&#xff0c;都会推荐你学测试。 首先必须声明&#xff0c;能在前端开发、测试、后端&#xff08;主要是Java&#xff09;这三个岗位中进行选择&#…

yum镜像源更新很慢,不管是阿里源还是清华源

今天想要再Centos7上安装docker测试&#xff0c;但是发现不管是阿里源还是清华源 yum makecache都更新的特别慢。有大佬知道啥原因不&#xff1f; 坐标成都&#xff0c;联通宽带300M

zabbix安装Grafana

一、web访问 https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-4.6.1-1.x86_64.rpm [rootserver ~] yum localinstall -y grafana-4.6.1-1.x86_64.rpm //yum方式安装本地rpm并自动解决依赖关系 [rootserver ~] grafana-cli plugins install alexanderzob…

分布式 RPC 框架HSF

分布式 RPC 框架HSF 概述HSF架构调用方式优势应用场景 概述 HSF (High-speed Service Framework)&#xff0c;高速服务框架&#xff0c;是在阿里巴巴内部广泛使用的分布式 RPC 服务框架。HSF 作为阿里巴巴的基础中间件&#xff0c;联通不同的业务系统&#xff0c;解耦系统间的…

Network Dissection 论文阅读笔记

Network Dissection 论文阅读笔记 1. 简介2. 网络刨析2.1 深度视觉表征的可解释性的测量步骤2.2 数据集2.3 可解释神经元评分 3. 实验3.1 对解释的人类评价3.2 Measurement of Axis-Aligned Interpretability3.3 理解层概念3.4 网络架构和监督3.5 训练条件 vs 可解释性3.6 网络…