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

创建数据库

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项目(此步骤省略)
链接: 百度网盘
在主目录下创建lib目录添加jar包 右击jar选择Add as Library 在选择相对应选择即可添加成功

创建实体类

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/vue@2.6.14/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>

实现效果图

在这里插入图片描述

  • 14
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例: 1. 创建一个Spring Boot项目 使用Spring Initializr创建一个新的Spring Boot项目,选择Web和MyBatis作为依赖项。 2. 配置数据源 在application.properties文件中添加以下内容: ``` spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false spring.datasource.username=root spring.datasource.password=root ``` 注意:这是一个示例,您需要将其替换为您自己的数据库配置。 3. 定义数据模型 创建一个Java类来表示数据库中的表。例如,如果您有一个名为“user”的表,则可以创建以下类: ```java public class User { private Long id; private String username; private String password; // 省略 getter 和 setter 方法 } ``` 4. 创建Mapper接口 创建一个Mapper接口来定义SQL操作。例如,如果您想查询用户,则可以创建以下接口: ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(@Param("id") Long id); } ``` 5. 创建RESTful API 创建一个控制器类来处理HTTP请求和响应。例如,如果您想获取用户,则可以创建以下控制器: ```java @RestController @RequestMapping("/api") public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/users/{id}") public User getUserById(@PathVariable Long id) { return userMapper.getUserById(id); } } ``` 6. 创建Vue.js应用程序 使用Vue CLI创建一个新的Vue.js应用程序。在Vue.js应用程序中,使用axios库从RESTful API获取数据。 7. 编写Vue组件 创建Vue组件来显示从API获取的数据。例如,如果您想显示用户的详细信息,则可以创建以下组件: ```vue <template> <div> <h1>{{ user.username }}</h1> <p>{{ user.password }}</p> </div> </template> <script> import axios from 'axios'; export default { data() { return { user: {} }; }, mounted() { axios.get('/api/users/1') .then(response => { this.user = response.data; }); } }; </script> ``` 8. 运行应用程序 运行Spring Boot应用程序和Vue.js应用程序,并访问Vue.js应用程序以查看结果。 以上是一个简单的前后端分离的代码示例,您可以根据自己的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值