SpringBoot实现CURD

SpringBoot实现CURD

 项目列表

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lin</groupId>
    <artifactId>springboot0711</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot0711</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>




        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency><dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

Bean

User

package com.lin.springboot0711.Bean;

public class User {
    private int id;
    private String name;
    private String password;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

 Controller  

 ModifyUserController

package com.lin.springboot0711.Controller;

import com.lin.springboot0711.Bean.User;
import com.lin.springboot0711.Service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ModifyUserController {

    @Resource
    UserService userService;
    //查询所有用户
    @RequestMapping("/users")
    public String showUsers(ModelMap modelMap){
        List<User> userList=userService.queryAllUser();
        modelMap.addAttribute("userList",userList);
        return "users";
    }


//    新增用户
    @RequestMapping("addUser")
    @ResponseBody
    public Map addUser(User user){
        int flag=userService.addUser(user);
        Map<String,Object>map=new HashMap<String ,Object>();
        if (flag==1) {
            map.put("msg","新增用户成功");
            return map;
        }
        else {
            map.put("msg","新增用户失败");
            return map;
        }
    }
//    根据用户ID删除用户信息
    @RequestMapping(value = "/deleteUser+{id}")
    public String dropUser(@PathVariable("id")String id ,ModelMap modelMap){
      int flag=userService.dropUser(id);
      List<User>userList=userService.queryAllUser();
      modelMap.addAttribute("userList",userList);
      if (flag==1){
          return "users";
      }else
      {
          return "error";
      }
    }
//    根据用户ID查询用户信息
    @RequestMapping("/user+{id}")
    public String queryUser(@PathVariable("id") String id,ModelMap modelMap){
        User user=userService.queryUserById(id);
        modelMap.addAttribute("user",user);
        return "userInfo";
    }
//    根据用户ID来修改用户信息
    @RequestMapping("/modifyUser")
    @ResponseBody
    public Map modifyUser(User user){
        int flag=userService.modifyUser(user);
        Map<String,Object>map =new HashMap<>();
        if (flag==1){
            map.put("msg","修改用户信息成功");
            return map;
        }
        else {
            map.put("msg", "修改用户信息失败");
            return map;
        }
    }


}

DAO

package com.lin.springboot0711.Dao;

import com.lin.springboot0711.Bean.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;


public interface UserMapper {
    public User getInfo(@Param("name") String name,@Param("password") String password);

    public User selectUserById(String id);

    public  int insertUser(User user);

    int updateUser(User user);

    int deleteUser(String id);

    List<User> getAllUser();
}

Service 

 

package com.lin.springboot0711.Service;

import com.lin.springboot0711.Bean.User;

import java.util.List;

public interface UserService {
    User loginIn(String name,String password);

    User queryUserById(String id);

    int addUser(User user);

    int dropUser(String id);

    int modifyUser(User user);

    List<User>queryAllUser();
}

ServiceImpl

 

package com.lin.springboot0711.ServiceImpl;

import com.lin.springboot0711.Bean.User;
import com.lin.springboot0711.Dao.UserMapper;
import com.lin.springboot0711.Service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
//    将DAO注入Service层
    @Resource
    private UserMapper userMapper;


    @Override
    public User loginIn(String name,String password){
        return userMapper.getInfo(name,password);
    }

    @Override
    public User queryUserById(String id){
        return userMapper.selectUserById(id);
    }

    @Override
    public int addUser(User user){
        int aFlag=userMapper.insertUser(user);
        return aFlag;
    }

    @Override
    public int dropUser(String id){
        int dFlag=userMapper.deleteUser(id);
        return  dFlag;
    }

    @Override
    public int modifyUser(User user){
        int mFlag=userMapper.updateUser(user);
        return mFlag;
    }

    @Override
    public List<User>queryAllUser(){
        return userMapper.getAllUser();
    }
}


Springboot0711Application

package com.lin.springboot0711;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
@MapperScan("com.lin.springboot0711.Dao")
public class Springboot0711Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot0711Application.class, args);
    }

}

 mapper  UserMapper.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lin.springboot0711.Dao.UserMapper">

    <select id="getInfo" resultType="com.lin.springboot0711.Bean.User">
        SELECT * FROM user
        WHERE
     name = #{name} AND password = #{password}
    </select>
<!--    根据ID查询用户信息-->
    <select id="selectUserById"  parameterType="String" resultType="com.lin.springboot0711.Bean.User">
        select * from user where id=#{id};
    </select>
<!--    插入新用户 id自增-->
    <insert id="insertUser" parameterType="com.lin.springboot0711.Bean.User" useGeneratedKeys="true" keyProperty="id">
        insert into user(name, password) VALUES (#{name},#{password});
    </insert>
    <delete id="deleteUser" parameterType="String">
        delete  from user where id=#{id};
    </delete>
    <!--根据ID修改用户信息,返回数据库操作影响行数,为0则是失败-->
    <update id="updateUser" parameterType="com.lin.springboot0711.Bean.User">
        update user set name=#{name} ,password=#{password} where id=#{id};
    </update>
    <select id="getAllUser" resultType="com.lin.springboot0711.Bean.User">
        select * from user;
    </select>

</mapper>

layui框架包(空间查看)

 

 login.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form role="form" action = "/loginIn" method="post">
    账号:<input type="text" id="name" name = "name"> <br>
    密码:<input type="password" id = "password" name = "password"> <br>
    <input type="submit" id = "login" value = "login">
</form>

</body>
</html>

error.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
<h1>登录失败!</h1>
</body>
</html>

success.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>

 userInfo.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>UserInfo</title>
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div id="modifyUser">
    <form name="modifyUser">
        <div class="form-group">
            <label for="id">ID:</label>
            <input type="text" class="form-control" name="id" id="id" th:value="${user.getId()}" disabled>
        </div>
        <div class="form-group">
            <label for="name">name:</label>
            <input type="text" class="form-control" name="name" id="name" th:value="${user.getName()}">
        </div>
        <div class="form-group">
            <label for="pwd">Password:</label>
            <input type="text" class="form-control" name="pwd" id = "pwd" th:value="${user.getPassword()}">
        </div>
<!--        <div class="form-check">-->
<!--            <label for="role">role:</label>-->
<!--            <select class="form-control" name="role" id = "role" th:value="${user.getRole()}">-->
<!--                <option th:selected="${user.getRole()=='admin'}" value = "admin">admin</option>-->
<!--                <option th:selected="${user.getRole()=='user'}" value = "user">user</option>-->
<!--            </select>-->
<!--        </div>-->
    </form>
    <button id = "modify">ModifyUser</button>
</div>
<script >
    //字符串判空方法
    function isBlank(str){
        if(str == "" || str == null || str == undefined){
            return true;
        }else {
            return false;
        }
    }
    //添加用户js响应事件
    $("#modify").click(function(){
        var id = $("#id").val();
        var name = $("#name").val();
        var password = $("#pwd").val();

        //判断是否有未填项
        if(isBlank(name) || isBlank(password) ){
            window.confirm("请完善信息");
        }else {
            var param = {
                "id": id,
                "name": name,
                "password": password

            };
            $.ajax({
                url:"/modifyUser", //请求url
                data: param,    //请求参数
                async: true,    //是否异步
                success: function f(result) {
                    window.confirm(result.msg); //修改用户信息成功提示框
                    location.href = "users";    //重新加载界面,同步数据库信息
                }
            });

        }

    });
</script>
</body>
</html>

 

 users.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Users</title>
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div id = "selectResult">
    <table class="table table-dark table-hover">
        <thead>
        <tr>
            <th>用户ID</th>
            <th>用户名称</th>
            <th>用户密码</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user : ${userList}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.password}"></td>

            <td>
                <a th:href = "@{/user+{id}(id=${user.id})}">修改</a>
                <a th:href = "@{/deleteUser+{id}(id=${user.id})}" id = "delete">删除</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>
<div id = "addUser">
    <form name="addUser">
        <div class="form-group">
            <label for="name">name:</label>
            <input type="text" class="form-control" name="name" id="name">
        </div>
        <div class="form-group">
            <label for="pwd">Password:</label>
            <input type="password" class="form-control" name="pwd" id = "pwd">
        </div>
<!--        <div class="form-check">-->
<!--            <label for="role">role:</label>-->
<!--            <select class="form-control" name="role" id = "role">-->
<!--                <option>admin</option>-->
<!--                <option>user</option>-->
<!--            </select>-->
<!--        </div>-->
    </form>
    <button id = "add">AddUser</button>

</div>

<script >
    //字符串判空方法
    function isBlank(str){
        if(str == "" || str == null || str == undefined){
            return true;
        }else {
            return false;
        }
    }
    //添加用户js响应事件
    $("#add").click(function(){
        var name = document.forms["addUser"]["name"].value;
        var password = document.forms["addUser"]["pwd"].value;
        //判断是否有未填项
        if(isBlank(name) || isBlank(password) ){
            window.confirm("请完善信息");
        }else {
            var param = {
                "name": name,
                "password": password
            };
            $.ajax({
                url:"/addUser", //请求url
                data: param,    //请求参数
                async: true,    //是否异步
                success: function f(result) {
                    window.confirm(result.msg); //新增用户成功提示框
                    location.href = "users";    //重新加载界面,同步数据库信息
                }
            });

        }

    });
</script>
</body>
</html>

 

 application.yml

 

spring:
  datasource:
    name: springboot  #数据库名
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
    username:   #用户名
    password:   #密码
    driver-class-name: com.mysql.cj.jdbc.Driver  #数据库链接驱动
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.lin.springboot0711.Bean

操作过程

 

说明

 该项目是一个简单的CURD  参考GitHub一个小的项目修改  

附上GitHub地址:https://github.com/redesperado/test1.git

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[email protected]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值