首页 > 其他分享 >Springboot + bootstrap 实现 增删改查

Springboot + bootstrap 实现 增删改查

时间:2022-10-29 17:11:48浏览次数:53  
标签:username Springboot bootstrap 改查 id User import public String

  • SpringBoot + bootstrap 配合 mysql 实现增删改查功能

  • 创建项目

  • 打开 idea 工具 ----   点击 File --- new --- Project 创建springBoot 项目工程,
  • 版本统一: 我使用的      mysql5.7         maven3.6.3       jdk1.8      idea2021.2
  •  

    进行 添加jar包配置

 

创建Springboot 工程好后,可以查看一下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.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.csq</groupId>
    <artifactId>csqtest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>csqtest</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-web</artifactId>
        </dependency>
<!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>

<!--        mysql连接器-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

<!--阿里数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!--        获取页面session对象request对象response对象 HttpServletXXX jar包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!--        json转换工具包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</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>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>org.apache.tomcat.embed</groupId>-->
<!--            <artifactId>tomcat-embed-core</artifactId>-->
<!--            <version>9.0.62</version>-->
<!--        </dependency>-->
    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 如果不配置fork,devtools就不会起作用,devtools是前端开发工具-->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
  • 完成pom.xml 后,下面我们创建mysql数据库
  • CREATE TABLE `user` (
      `id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `username` varchar(255) DEFAULT NULL COMMENT '姓名',
      `password` varchar(255) DEFAULT NULL COMMENT '密码',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;

    可以手动创建一条数据先

    完成数据库后,先给大家看一下我的整体实现增删改查的包

  •  

    下面我们创建一个实体类,pojo   -----   User.java

  • package com.csq.csqtest.pojo;
    
    public class User {
        private Integer id;
        private String username;
        private String password;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        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 User(Integer id,String username,String password) {
            this.id=id;
            this.username=username;
            this.password=password;
        }
        public User() {
    
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }

    创建方法接口 service --- UserService

  • package com.csq.csqtest.service;
    
    import com.csq.csqtest.pojo.User;
    
    import java.util.List;
    
    public interface UserService {
        //查询全部
        List<User> findAll();
        //新增数据
        int save(User user);
        //删除数据
        Integer delete(int id);
        //根据id查找
        User get(int id);
        //更新数据
        int update(User user);
    
    //    //根据姓名查询
    //    User get(String username);
    }

    实现方法  impl ---- UserServiceImpl.java

  • package com.csq.csqtest.service.impl;
    
    import com.csq.csqtest.mapper.UserMapper;
    import com.csq.csqtest.pojo.User;
    import com.csq.csqtest.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
        @Autowired
        private UserMapper userMapper;
    
    
        @Override
        public List<User> findAll() {
            return userMapper.findAll();
        }
    
        @Override
        public int save(User user) {
            return userMapper.save(user);
        }
    
        @Override
        public Integer delete(int id) {
            return userMapper.delete(id);
        }
    
        @Override
        public User get(int id) {
            return userMapper.get(id);
        }
    
    //    @Override
    //    public User get(String username) {
    //        return userMapper.get(username);
    //    }
    
        @Override
        public int update(User user) {
            return userMapper.update(user);
        }
    }

    创建mapper --- UserMapper.java

  •   

    package com.csq.csqtest.mapper;
    
    import com.csq.csqtest.pojo.User;
    import org.apache.ibatis.annotations.*;
    
    import java.util.List;
    
    @Mapper
    public interface UserMapper {
        //查询全部
        @Select("select * from user")
        List<User> findAll();
    
        //新增数据
        @Insert("insert into user (username,password) values (#{username},#{password})")
        public int save(User user);
    
        //删除数据
        @Delete("delete from user where id=#{id}")
        public int delete(int id);
    
        //根据id查找
        @Select("select * from user where id=#{id}")
        public User get(int id);
    
    
        //根据username查询
    //    @Select("select * from user where id=#{id}")
    //    public User get(String username);
    
    
        //更新数据
        @Update("update user set username=#{username},password=#{password} where id=#{id}")
        public int update(User user);
    
    }

    创建controller   ----   UserControl.java

  • package com.csq.csqtest.controller;
    
    import com.csq.csqtest.pojo.User;
    import com.csq.csqtest.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.List;
    import java.util.Map;
    
    //控制层,导入Service层
    @Controller
    public class UserControl {
        @Autowired
        private UserService userService;
    
        //查询全部,在mvc中model层就是dao层,在java中无特殊含义就是模块
        @GetMapping("/index.html")
        public String userList(Map<String, List> result) {
            List<User> Users = userService.findAll();
            result.put("users", Users);
            return "index";
        }
    
        //新增数据
        @PostMapping("/add")
        public String save(User user) {
            userService.save(user);
            return "redirect:/index.html";
        }
    
        //删除数据,
        @RequestMapping("/delete/{id}")
        public String delete(@PathVariable Integer id, HttpServletResponse servletResponse) throws IOException {
            userService.delete(id);
            System.out.println("delete方法执行");
            return "redirect:/index.html";
        }
    
    
        //根据id进行修改,需要先获得该id对应的值,所以需要get请求
        @GetMapping("/updatePage/{id}")
        public String updatePage(Model model, @PathVariable int id) {
            User users = userService.get(id);
            model.addAttribute("users", users);
            return "modifie";
        }
    
        @PutMapping("/update")
        public String updateUser(Model model, User user, HttpServletRequest request) {
            String id = request.getParameter("id");
            User userById = userService.get(Integer.parseInt(id));
            userService.update(user);
            System.out.println(user);
            return "redirect:/index.html";
        }
    
    
        //根据id查询
        @RequestMapping("/get")
        public String get(Model model, int id) {
            User users = userService.get(id);
            model.addAttribute("users", users);
            return "index";
        }
    
    //    @RequestMapping("/getusername")
    //    public String get(Model model, String username) {
    //        User users = userService.get(username);
    //        model.addAttribute("users", users);
    //        return "index";
    //    }
    }

    接下来实现配置application.yml

  • spring:
      web:
        resources:
          static-locations: classpath:/static/,classpath:/templates/
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/zls?useSSL=false&useUnicode=true&characterEncoding=utf-8
        username: root    //账号
        password: 123456   //密码
        driver-class-name: com.mysql.cj.jdbc.Driver
      mvc:
        hiddenmethod:
          filter:
            enabled: true
    
    
      devtools:
        restart:
          enabled: true #设置开启热部署
      freemarker:
        cache: false #页面不加载缓存,修改即使生效
    mybatis:
      configuration:
        map-underscore-to-camel-case: true #下划线驼峰设置
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   # 打印SQL语句
    
    
    server:
      port: 8082    //端口号

    然后访问:

     

    空白是因为数据库没有数据,访问成功。

     

    下面开始填写前端,调用前端框架: 

    bootstrap

     

     

     

     在 templates 里面创建一个html   ---  index.html

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<style>
    a{
        color: #ffffff;
    }
    h1{
        /*文字对齐*/
        text-align: center;
    }
    th{
        text-align: center;
    }
</style>

<body>
<div>
<h1 style="color: darkcyan">信息系统管理</h1>
<!--    <p style="text-align: center">-->
<!--     <button class="btn btn-primary">搜索</button>-->
<!--        <input type="text" style="width: 300px; height: 33px; /">-->
<!--    </p>-->
    <form action="/get" method="post">
        输入编号:<input class="form-control" type="text" th:value="${#ids}" name="id"><br>
        <button class="btn btn-primary btn-lg btn-block">查询</button>
    </form>

<!--    <form action="/getusername" method="post">-->
<!--        输入姓名:<input class="form-control" type="text" th:value="${#uris}" name="username"><br>-->
<!--        <button class="btn btn-primary btn-lg btn-block">查询</button>-->
<!--    </form>-->
</div>
<!--table-striped:斑马线格式,table-bordered:带边框的表格,table-hover:鼠标悬停高亮的表格-->
<table class="table table-striped table-bordered table-hover text-center">
    <thead>
    <tr style="text-align:center">
<!--        th标签定义html表格中的表头单元格-->
        <th>编号</th>
        <th>姓名</th>
        <th>密码</th>
        <th>操作</th>
    </tr>
    </thead>
<!--tr标签定义html表格中的所有行-->
<!--    遍历集合,如果被遍历的变量users为null或者不存在,则不会进行遍历,也不会报错-->
    <tr th:each="user:${users}">
<!--        td标签定义html表格中的标准单元格-->
        <td th:text="${user.id}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${user.password}"></td>
        <td>
<!--         a标签用来定义超链接 href表示超链接-->
            <a class="btn btn-primary" th:href="@{'/updatePage/'+${user.id}}">更改</a>
            <a class="btn btn-danger" th:href="@{'/delete/'+${user.id}}">删除</a>
        </td>
    </tr>
</table>
<a href="/add.html"> <input type="button" value="添加用户" class="btn btn-block" style="color: cadetblue; background-color: lightblue"/></a>
<!--<button class="btn btn-block" style="color: cadetblue; background-color: lightblue"><a href="/add.html">添加用户</a></button>-->

</body>

</html>

记住,数据库一定要有数据,现在开始访问,   成功访问 :

 

 

注意自己的端口号访问的时候:

 

 

下面开始实现提交功能---   add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

<div style="width:600px;height:100%;margin-left:270px;">
    <form action="/add" method="post">
<!--        form-control给input添加这个class后就会使用bootstrap自带的input框-->
        用户名:<!--/*@thymesVar id="password" type=""*/-->
        <input class="form-control" type="text" th:value="${username}" name="username"><br>
        密 码:<!--/*@thymesVar id="password" type="ch"*/-->
        <input class="form-control" type="text" th:value="${password}" name="password"><br>
        <button class="btn btn-primary btn-lg btn-block">保存</button>
    </form>
</div>

</body>
</html>

开始进行访问测试有没有成功::

 

 访问成功,添加数据成功

 

 

下面进行修改数据:::

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改用户</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div style="width:600px;height:100%;margin-left:270px;">
    <form action="/update" method="post">
        <input name="_method" type="hidden" value="put">
        ID:<input class="form-control"  type="text" th:value="${users.id}" name="id"><br>
        用户名:<input class="form-control" type="text" th:value="${users.username}" name="username"><br>
        密 码:<input class="form-control" type="text" th:value="${users.password}" name="password"><br>
        <button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
    </form>
</div>

</body>
</html>

 

 成功::

 

 

想要源码,麻烦关注私聊,谢谢!

 

标签:username,Springboot,bootstrap,改查,id,User,import,public,String
From: https://www.cnblogs.com/zengxiangcai/p/16839124.html

相关文章

  • SpringBoot推送微信测试公众号信息
    1、登陆微信公众平台测试号2、扫码关注3、新建模版参数需以{{开头,以.DATA}}结尾,ex:{{msg.DATA}},代码里面替换就可以了templateMessage.addData(newWxMpTemplateDat......
  • 安装Redis并在springboot项目中使用redis
    一、下载redis1.1官网下载 1.2将其添加到服务上,并使其开机自启动 二、下载redis可视化工具(下不下都行) 三、将redis集成到我们的springboot项目中3.1首先是引......
  • SpringBoot 解决跨域问题代码
     packagecom.example.demo.gs;importorg.springframework.context.annotation.Configuration;importjavax.servlet.*;importjavax.servlet.annotation.WebFilter......
  • springboot 临时关闭 springSecurity 权限认证
    Springboot项目有时候本地测试,但是有springsecurity的权限认证,很不方便测试。临时关闭方式启动类上去掉配置:@SpringBootApplication(exclude={SecurityAutoConfigur......
  • 2流高手速成记(之五):Springboot整合Shiro实现安全管理
    废话不多说,咱们直接接上回上一篇我们讲了如何使用Springboot框架整合Nosql,并于文章最后部分引入了服务端Session的概念而早在上上一篇中,我们则已经讲到了如何使用Springb......
  • Springboot错误:Unable to start embedded Tomcat server
    报错内容/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/bin/java-XX:TieredStopAtLevel=1-noverify-Dspring.output.ansi.enabled=always-javaagent:/......
  • SpringBoot Starter缘起
    SpringBoot通过SpringBootStarter零配置自动加载第三方模块,只需要引入模块的jar包不需要任何配置就可以启用模块,遵循约定大于配置的思想。那么如何编写一个SpringBootSt......
  • springboot启动默认连接数据库问题
    这里是给新手介绍的springboot默认启动是连接数据库的经常很多人蒙蔽,//无数据源启动@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,DataSo......
  • springboot像springnvc那样访问视图
    1.SpringBoot访问静态资源的位置(优先级按以下顺序)classpath默认就是resources,所以classpath:/static/就是resources/static/classpath:/META‐INF/resources/cl......
  • 【SpringBoot】引入mybatis及连接Mysql数据库
    创建一个SpringBoot项目其他不赘叙了,引入MyBaties、MySql依赖编辑 创建mysql表CREATETABLEsp_users(`id`INTPRIMARYKEY,`username`VARCHAR(30),`age`INT);刚......