首页 > 数据库 >【vue+jdbc实现数据库操作java web前后分离版】

【vue+jdbc实现数据库操作java web前后分离版】

时间:2024-07-22 23:55:14浏览次数:18  
标签:username web jdbc java String public id conn pstmt

创建数据库

drop table if exists users;
create table users
(
  id               bigint(20)      not null   auto_increment  comment '用户id',
  username         varchar(100)    default ''                 comment '用户名',
  phone            varchar(100)    default ''                 comment '电话',
  email            varchar(100)    default ''                 comment '邮箱',
  primary key (id)
) engine=innodb comment='用户表';

后端代码

根据模版创建javaweb项目(此步骤省略)

创建实体类

public class User {

    private int id;
    private String username;
    private String phone;
    private String email;

    public User() {
    }

    public User(int id, String username, String phone, String email) {
        this.id = id;
        this.username = username;
        this.phone = phone;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPhone() {
        return phone;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

jdbc连接数据库

public class JdbcConnection {
    private static Connection conn = null;

    private static final String username = "你的账号";  //默认root
    private static final String password = "你的密码";

    public static Connection dbConnection() {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException ce) {
            System.out.print(ce);
        }
        try {
            String url = "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException ce) {
            System.out.print(ce);
        }
        return conn;
    }

    public static void closeConnection(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeConnection(Connection conn, PreparedStatement pstmt) {
        try {
            if (pstmt != null)
                pstmt.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

创建Servlet

@WebServlet("/users/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserService();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户列表
        List<User> users = userService.getAllUsers();
        String json = new Gson().toJson(users);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 添加用户
        User user = new GsonBuilder()
                .registerTypeAdapter(int.class, new IntTypeAdapter())
                .registerTypeAdapter(Integer.class, new IntTypeAdapter()).create()
                .fromJson(req.getReader(), User.class);
        userService.addUser(user);
        System.out.println("添加成功" + user);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 更新用户
        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            String[] pathParts = pathInfo.split("/");
            if (pathParts.length > 1) {
                int id = Integer.parseInt(pathParts[1]);
                User user = new Gson().fromJson(req.getReader(), User.class);
                userService.updateUser(id, user);
                System.out.println("编辑成功" + id);
            }
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 删除用户
        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            String[] pathParts = pathInfo.split("/");
            if (pathParts.length > 1) {
                int id = Integer.parseInt(pathParts[1]);
                userService.deleteUser(id);
                System.out.println("删除成功" + id);
            }
        }

    }
}

链接: 百度网盘
在主目录下创建lib目录添加jar包 右击jar选择Add as Library 在选择相对应选择即可添加成功

工具类

public class IntTypeAdapter extends TypeAdapter<Number> {

    @Override
    public void write(JsonWriter out, Number value)
            throws IOException {
        out.value(value);
    }

    @Override
    public Number read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        try {
            String result = in.nextString();
            if ("".equals(result)) {
                return null;
            }
            return Integer.parseInt(result);
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }
}

数据库操作

public class UserService {

    // 查询用户
    public List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 连接数据库
            conn = JdbcConnection.dbConnection();
            // 查询产品信息
            String querySql = "SELECT id, username, phone, email FROM users";
            pstmt = conn.prepareStatement(querySql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String phone = rs.getString("phone");
                String email = rs.getString("email");
                User user = new User(id, username, phone, email);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            JdbcConnection.closeConnection(conn, pstmt, rs);
        }
        return users;
    }


    // 添加用户
    public void addUser(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 连接数据库
            conn = JdbcConnection.dbConnection();
            // 添加用户
            String addSql = "INSERT INTO users(username, phone, email) VALUES(?, ?, ?)";
            pstmt = conn.prepareStatement(addSql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPhone());
            pstmt.setString(3, user.getEmail());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            JdbcConnection.closeConnection(conn, pstmt);
        }

    }

    // 修改用户信息
    public void updateUser(int id, User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 连接数据库
            conn = JdbcConnection.dbConnection();
            // 更新产品信息
            String updateSql = "UPDATE users SET phone = ?, email = ?, username = ? WHERE id = ?";
            pstmt = conn.prepareStatement(updateSql);
            pstmt.setString(1, user.getPhone());
            pstmt.setString(2, user.getEmail());
            pstmt.setString(3, user.getUsername());
            pstmt.setInt(4, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            JdbcConnection.closeConnection(conn, pstmt);
        }

    }

    // 删除用户
    public void deleteUser(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 连接数据库
            conn = JdbcConnection.dbConnection();
            // 删除用户
            String deleteSql = "DELETE FROM users WHERE id = ?";
            pstmt = conn.prepareStatement(deleteSql);
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            JdbcConnection.closeConnection(conn, pstmt);
        }
    }
}

跨域

@WebFilter(filterName = "Filter_CrossOrigin",urlPatterns = "/*")
public class Filter_CrossOrigin implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        request1.setCharacterEncoding("utf-8");
        response1.setHeader("Access-Control-Allow-Origin", request1.getHeader("origin"));
        response1.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response1.setHeader("Access-Control-Max-Age", "3600");
        response1.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        response1.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request1, response1);
    }
}

前端代码

测试时注意后端端口和路径 我的是http://localhost:8080/j_vue_war_exploded/users

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Management System</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>

<div id="app">
    <!-- 用户列表 -->
    <table>
        <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        <tr v-for="user in users">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.phone }}</td>
            <td>{{ user.email }}</td>
            <td>
                <button @click="editUser(user)">编辑</button>
                <button @click="deleteUser(user.id)">删除</button>
            </td>
        </tr>
    </table>

    <!-- 添加/编辑用户表单 -->
    <form @submit.prevent="submitForm">
        <input type="hidden" v-model="form.id">
        <input type="text" v-model="form.username" placeholder="Username">
        <input type="text" v-model="form.phone" placeholder="Phone">
        <input type="email" v-model="form.email" placeholder="Email">
        <button type="submit">添加/修改</button>
    </form>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            users: [],
            form: {
                id: '',
                username: '',
                phone: '',
                email: ''
            }
        },
        methods: {
            fetchUsers() {
                axios.get('http://localhost:8080/j_vue_war_exploded/users').then(response => {
                    this.users = response.data;
                });
            },
            editUser(user) {
                this.form = {...user};
            },
            deleteUser(id) {
                axios.delete(`http://localhost:8080/j_vue_war_exploded/users/${id}`).then(() => {
                    this.fetchUsers();
                });
            },
            submitForm() {
                const method = this.form.id ? 'put' : 'post';
                const url = this.form.id ? `http://localhost:8080/j_vue_war_exploded/users/${this.form.id}` : 'http://localhost:8080/j_vue_war_exploded/users';
                axios[method](url, this.form).then(() => {
                    this.fetchUsers();
                    this.form = { id: '', username: '', phone: '', email: '' };
                });
            }
        },
        mounted() {
            this.fetchUsers();
        }
    });
</script>

</body>
</html>

实现效果图

在这里插入图片描述

标签:username,web,jdbc,java,String,public,id,conn,pstmt
From: https://blog.csdn.net/weixin_46198124/article/details/140621177

相关文章

  • 学习java第一百三十八天
    Bean的作用域1、singleton:单例,Spring中的bean默认都是单例的。2、prototype:每次请求都会创建一个新的bean实例。3、request:每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTPrequest内有效。4、session:每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTPsession......
  • 《Java初阶数据结构》----1.<时间复杂度&空间复杂度计算>
    目录算法效率:一、时间复杂度的计算1.1时间复杂度的表示1.2常见时间复杂度大小排序 1.3计算示例冒泡排序的时间复杂度二分查找的时间复杂度 阶乘递归factorial的时间复杂度斐波那契递归的时间复杂度二、空间复杂度的计算冒泡排序的空间复杂度计算fibonacci的空间复......
  • Web劫持详解:原理、实现方式及防护方法
    Web劫持是一种常见且危险的网络攻击方式,攻击者通过篡改网页内容或重定向用户请求,达到窃取信息、传播恶意软件或其他非法目的。本文将详细讲解Web劫持的原理、实现方式及有效防护方法,并指出在防护过程中需要注意的事项。一、Web劫持的原理Web劫持主要是通过篡改或控制用户的浏......
  • Java学习——多线程
    1.多线程介绍1.1什么是多线程具有多线程能力的计算机因有硬件支持而能够在同一时间执行多个线程,提升性能。1.2并发与并行并行:在同一时刻,有多个指令在多个CPU上同时执行。并发:在同一时刻,有多个指令在单个CPU上交替执行。高并发是什么意思:cpu2核4线程表示可并行处理4......
  • 如何理解JAVA的编码格式是Unicode
    背景今天看以前的JAVA视频,发现课件里面写着JAVA的内部的编码格式是Unicode。这句话,突然勾起了我的好奇心。因为的JAVA代码文件都是UTF8编码,怎么跟Unicode扯上关系的呢?我去问了一下AI,然后整理了一下Unicode是JAVA编译器的读取class文件使用的编码假设,我的如下代码是UTF-8编......
  • java-cglib动态代理原理
    cglib使用1.引入依赖<!--添加cglib依赖--><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>3.3.0</version>&......
  • java编程 2
    1,比较运算符,比g和103是否相等???代码:publicclassbj{   publicstaticvoidmain(String[]args){       charq='g';       intw=103;       if(q==103){   System.out.println("g和103是相等的");       }else{......
  • Java编程 3
    1.轿车平均加速度   =速度的变化量/时间的变化量   轿车用了8.7秒从0千米加速到每小时100千米代码:publicclassvp{   publicstaticvoidmain(String[]args){   ints0=0;//定义变量值   ints1=(int)100.11;//浮点型强制转化成整型  ......
  • 使用Java和Flyway进行数据库版本控制
    使用Java和Flyway进行数据库版本控制大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天,我们来深入探讨如何使用Java和Flyway进行数据库版本控制。一、Flyway简介Flyway是一个数据库迁移工具,它能够帮助开发者管理数据库版本,自动应用数据库迁移脚本,确保......
  • Java中的元编程与动态代理技术
    Java中的元编程与动态代理技术大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天,我们将探讨Java中的元编程与动态代理技术。这些技术使得Java开发者能够在运行时动态地生成、修改代码或行为,增强了代码的灵活性和扩展性。一、元编程概述元编程(Metaprogr......