IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> Servlet项目源码——servlet连接JDBC实现增删改查 -> 正文阅读

[大数据]Servlet项目源码——servlet连接JDBC实现增删改查

database.properties:

# 数据库连接对象基础配置
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/hyqwsq?useUnicode=true&characterEncoding=UTF-8
username = root
password = 333

# 配置连接池相关内容
# 初始容量
initialSize = 10
# 最大连接数量
maxActive = 20
# 最小空闲连接
minIdle = 5
# 超时
maxWait = 3000

dao

接口:

package com.hyq.servletProject.dao;

import com.hyq.servletProject.entity.Admin;

import java.util.List;

public interface AdminDao {
    public int insert(Admin admin);
    public int delete(String username);
    public int update(Admin admin);
    public Admin select(String username);
    public List<Admin> selectAll();
}

实现类:

package com.hyq.servletProject.dao.impl;

import com.hyq.servletProject.dao.AdminDao;
import com.hyq.servletProject.entity.Admin;
import com.hyq.servletProject.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

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

public class AdminDaoImpl implements AdminDao {
    private QueryRunner queryRunner = new QueryRunner();
    @Override
    public int insert(Admin admin) {
        return 0;
    }

    @Override
    public int delete(String username) {
        return 0;
    }

    @Override
    public int update(Admin admin) {
        return 0;
    }

    @Override
    public Admin select(String username) {
        try {
            Admin admin = queryRunner.query(DbUtils.getConnection(),"select * from admin where username = ?;",new BeanHandler<Admin>(Admin.class),username);
            return admin;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Admin> selectAll() {
        try {
            List<Admin> admins = queryRunner.query(DbUtils.getConnection(),"select * from admin",new BeanListHandler<Admin>(Admin.class));
            return admins;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}


entity:

Admin:

package com.hyq.servletProject.entity;

public class Admin {
    private String username;
    private String password;
    private String phone;
    private String address;

    public Admin() {

    }

    public Admin(String username,String password,String phone,String address){
        this.username = username;
        this.password = password;
        this.phone = phone;
        this.address = address;
    }

    public String toString(){
        return "Admin{" +
                "username='" + username + '\'' +
                ",password+'" + password + '\'' +
                ",phone+'" + phone + '\'' +
                ",address+'" + address + '\'' +
                '}';
    }

    public String getUsername(){
        return username;
    }
    public void setUsername(String username){
        this.username = username;
    }

    public String getPassword(){
        return password;
    }
    public void setPassword(String password){
        this.password = password;
    }

    public String getPhone(){
        return phone;
    }
    public void setPhone(String password){
        this.password = password;
    }

    public String getAddress(){
        return password;
    }
    public void setAddress(String password){
        this.password = password;
    }
}


service:

接口:

package com.hyq.servletProject.service;

import com.hyq.servletProject.entity.Admin;

import java.util.List;

public interface AdminService {
    public Admin ligin(String username, String password);

    public List<Admin> showAllAdmin();
}

实现类:

package com.hyq.servletProject.service.impl;

import com.hyq.servletProject.dao.AdminDao;
import com.hyq.servletProject.dao.impl.AdminDaoImpl;
import com.hyq.servletProject.entity.Admin;
import com.hyq.servletProject.service.AdminService;
import com.hyq.servletProject.utils.DbUtils;

import java.util.List;

public class AdminServiceImpl implements AdminService {
    private AdminDao adminDao = new AdminDaoImpl();
    @Override
    public Admin ligin(String username, String password) {
        Admin result = null;
        try {
            DbUtils.begin();
            Admin admin = adminDao.select(username);
            if (admin != null) {
                if (admin.getPassword().equals(password)) {
                    result = admin;
                }
            }
            DbUtils.commit();
        }catch(Exception e){
            DbUtils.rollback();
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Admin> showAllAdmin() {
        List<Admin> admins = null;
        try {
            DbUtils.begin();
            admins = adminDao.selectAll();
            DbUtils.commit();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}


servlet:

LoginServlet:

package com.hyq.servletProject.servlet;

import com.hyq.servletProject.entity.Admin;
import com.hyq.servletProject.service.AdminService;
import com.hyq.servletProject.service.impl.AdminServiceImpl;

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.PrintWriter;

@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置字符集编码格式
        req.setCharacterEncoding("UTF-8");
        // 设置响应给客户端的结果也是以test/html;charset = UTF-8的格式
        resp.setContentType("test/html;charset = UTF-8");
        // 1.收参,通过req的getParameter()方法
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 2.调用业务逻辑,将数据传给业务逻辑层
        AdminService adminService = new AdminServiceImpl();     // new一个AdminService对象
        Admin admin = adminService.login(username,password);    // 调用AdminService的login方法传参

        // 3.处理结果
        PrintWriter printWriter = resp.getWriter();
        if(admin != null){
            // 响应给客户端一个结果页面,显示登录成功
            printWriter.println("<html>");
            printWriter.println(    "<head>");
            printWriter.println(        "<meta charset = 'UTF-8'>");
            printWriter.println(        "<title>结果页面</title>");
            printWriter.println(    "</head>");

            printWriter.println(    "<body>");
            printWriter.println(        "<div>");
            printWriter.println(            "<h1>登录成功!</h1>");
            printWriter.println(        "</div>");
            printWriter.println(    "</body>");
            printWriter.println("</html>");

        }else{
            printWriter.println("<html>");
            printWriter.println(    "<head>");
            printWriter.println(        "<meta charset = 'UTF-8'>");
            printWriter.println(        "<title>结果页面</title>");
            printWriter.println(    "</head>");

            printWriter.println(    "<body>");
            printWriter.println(        "<h1>登录失败!</h1>");
            printWriter.println(    "</body>");
            printWriter.println("</html>");

        }

    }

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

ShowAllAdminServlet:

package com.hyq.servletProject.servlet;

import com.hyq.servletProject.entity.Admin;
import com.hyq.servletProject.service.AdminService;
import com.hyq.servletProject.service.impl.AdminServiceImpl;

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.PrintWriter;
import java.util.List;

@WebServlet(value = "/showall")
public class ShowAllAdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // 1.调用业务逻辑功能
        AdminService adminService = new AdminServiceImpl();
        List<Admin> adminList = adminService.showAllAdmin();

        // 2.通过流打印结果显示
        PrintWriter printWriter = resp.getWriter();
        if(adminList != null){
            printWriter.println("<html>");
            printWriter.println(    "<head>");
            printWriter.println(        "<meta charset = 'UTF-8'>");
            printWriter.println(        "<title>显示所有</title>");
            printWriter.println(    "</head>");

            printWriter.println(    "<body>");
            printWriter.println(        "<table border = '1'>");
            printWriter.println(            "<tr>");
            printWriter.println(                "<td>username</td>");
            printWriter.println(                "<td>password</td>");
            printWriter.println(                "<td>phone</td>");
            printWriter.println(                "<td>address</td>");
            printWriter.println(            "</tr>");

            for(Admin admin : adminList){
                printWriter.println(            "<tr>");
                printWriter.println(                "<td>"+admin.getUsername()+"</td>");
                printWriter.println(                "<td>"+admin.getPassword()+"</td>");
                printWriter.println(                "<td>"+admin.getPhone()+"</td>");
                printWriter.println(                "<td>"+admin.getAddress()+"</td>");
                printWriter.println(            "</tr>");

            }
            printWriter.println(        "</table>");
            printWriter.println(    "</body>");
            printWriter.println("</html>");

        }else{
            printWriter.println("<html>");
            printWriter.println(    "<head>");
            printWriter.println(        "<meta charset = 'UTF-8'>");
            printWriter.println(        "<title>显示所有</title>");
            printWriter.println(    "</head>");

            printWriter.println(    "<body>");
            printWriter.println(        "<h3>当前没有数据</h3>");
            printWriter.println(    "</body>");
            printWriter.println("</html>");

        }
    }

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

AhowAllAdminController:

package com.hyq.servletProject.servlet;

import com.hyq.servletProject.entity.Admin;
import com.hyq.servletProject.service.AdminService;
import com.hyq.servletProject.service.impl.AdminServiceImpl;

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.util.List;

@WebServlet(value = "/showallcontroller")
public class ShowAllAdminController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 只负责调用业务逻辑功能
        AdminService adminService = new AdminServiceImpl();

        List<Admin> adminList = adminService.showAllAdmin();

        // request作用域存储数据
        req.setAttribute("admins",adminList);
        // 通过转发,跳转到显示结果的Servlet
        req.getRequestDispatcher("/showalljsp").forward(req,resp);
    }

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

ShowAllAdminJSP:

package com.hyq.servletProject.servlet;

import com.hyq.servletProject.entity.Admin;

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.PrintWriter;
import java.util.List;

@WebServlet("/showalljsp")
public class ShowAllAdminJSP extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        List<Admin> adminList = (List)req.getAttribute("admins");

        // 2.通过流打印结果显示
        PrintWriter printWriter = resp.getWriter();
        if(adminList != null){
            printWriter.println("<html>");
            printWriter.println(    "<head>");
            printWriter.println(        "<meta charset = 'UTF-8'>");
            printWriter.println(        "<title>显示所有</title>");
            printWriter.println(    "</head>");

            printWriter.println(    "<body>");
            printWriter.println(        "<table border = '1'>");
            printWriter.println(            "<tr>");
            printWriter.println(                "<td>username</td>");
            printWriter.println(                "<td>password</td>");
            printWriter.println(                "<td>phone</td>");
            printWriter.println(                "<td>address</td>");
            printWriter.println(            "</tr>");

            for(Admin admin : adminList){
                printWriter.println(            "<tr>");
                printWriter.println(                "<td>"+admin.getUsername()+"</td>");
                printWriter.println(                "<td>"+admin.getPassword()+"</td>");
                printWriter.println(                "<td>"+admin.getPhone()+"</td>");
                printWriter.println(                "<td>"+admin.getAddress()+"</td>");
                printWriter.println(            "</tr>");

            }
            printWriter.println(        "</table>");
            printWriter.println(    "</body>");
            printWriter.println("</html>");

        }else{
            printWriter.println("<html>");
            printWriter.println(    "<head>");
            printWriter.println(        "<meta charset = 'UTF-8'>");
            printWriter.println(        "<title>显示所有</title>");
            printWriter.println(    "</head>");

            printWriter.println(    "<body>");
            printWriter.println(        "<h3>当前没有数据</h3>");
            printWriter.println(    "</body>");
            printWriter.println("</html>");

        }
    }

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


utils:

DbUtils:

package com.hyq.servletProject.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DbUtils {
    // 创建数据库连接池对象
    private static DruidDataSource ds;
    // 新建ThreadLocal控制事务,,通过Connection存储
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();

    // 提供静态代码块,完成初始创建
    static {
        Properties properties = new Properties();
        InputStream inputStream = DbUtils.class.getResourceAsStream("/database.properties");
        try {
            properties.load(inputStream);
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = THREAD_LOCAL.get();

            try {
                if(connection == null) {
                    connection = ds.getConnection();
                    THREAD_LOCAL.set(connection);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        return connection;
    }

    public static void begin(){
        Connection connection = null;
        connection = getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void commit(){
        Connection connection = null;
        connection = getConnection();
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            closeAll(connection,null,null);
        }
    }

    public static void rollback(){
        Connection connection = null;
        connection = getConnection();
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            closeAll(connection,null,null);
        }
    }

    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
        try{
            if(resultSet != null){
                resultSet.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
                THREAD_LOCAL.remove();
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}


Web:

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action = "/untitled2_war_exploded/login" method = "post">
        <div>
            用户名:<input type = "test" name = "username" /></br>
            密码:<input type = "test" name = "password" /></br>
            <input type = "submit" value = "登录" />
        </div>
    </form>
</body>
</html>
  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2021-12-14 16:00:53  更:2021-12-14 16:02:22 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 12:03:13-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码