日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Spring Boot簡(jiǎn)易增刪改查(CRUD)案例

作者:LeBron Le 更新時(shí)間: 2022-07-16 編程語(yǔ)言

目錄

  • 項(xiàng)目架構(gòu)
    • 數(shù)據(jù)庫(kù)
    • POJO
    • Dao
    • Service
    • Controller
    • 前端頁(yè)面
    • 配置文件
    • 運(yùn)行

項(xiàng)目架構(gòu)

本項(xiàng)目為Spring Boot入門(mén)——增刪改查案例。
前端采用html + thymeleaf模板代替jsp
項(xiàng)目架構(gòu)如下:

.
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example
│   │   │       └── crud                          --業(yè)務(wù)功能模塊 即 CRUD
│   │   │           ├── controller                --Controller層
│   │   │           │    └── UserControl           
│   │   │           ├── dao                       --Dao層
│   │   │           │    └── UserDao              --Dao層接口         
│   │   │           ├── pojo                      --數(shù)據(jù)模型
│   │   │           │    └── User                 --請(qǐng)求體
│   │   │           ├── service                   --Service層
│   │   │           │    ├── impl                 --Service層接口的實(shí)現(xiàn)
│   │   │           │    │    └── UserServiceImpl 
│   │   │           │    └── UserService          --Service層接口
│   │   │           └── Application.java          --啟動(dòng)類(lèi)
│   │   └── resources
│   │       ├── static                            --靜態(tài)資源
│   │       ├── template                          --模板
│   │              ├── add.html                   --增加用戶(hù)頁(yè)面
│   │              ├── index.html                 --主頁(yè)面
│   │              └── modify.html                --修改用戶(hù)頁(yè)面
└── pom.xml                                       --項(xiàng)目依賴(lài)

數(shù)據(jù)庫(kù)

MySQL:v8.0.29
Navicat Premium 15
新建連接:crud
新建數(shù)據(jù)庫(kù):springboot_crud
:user
包含三個(gè)字段:id,username,password

user表如下:

id username password
1 Lebron 1111
2 Durant 2222
3 Curry 3333
4 Bryant 4444
5 Harden 5555

建表SQL語(yǔ)句:

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

POJO

pojo下包含實(shí)體類(lèi)User
實(shí)體類(lèi)有三個(gè)私有成員變量:idusernamepassword
這三個(gè)屬性分別與數(shù)據(jù)庫(kù)springboot_crud中的表user相對(duì)應(yīng)。
實(shí)體類(lèi)User包含帶參構(gòu)造方法、無(wú)參構(gòu)造方法、三個(gè)屬性對(duì)應(yīng)的getset方法,另外還包含一個(gè)重寫(xiě)的toString方法。

實(shí)體類(lèi)User.java

package com.example.crud.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 + '\'' +
                '}';
    }
    
}

Dao

dao下包含接口UserDao
注解@Mapper用于修飾接口UserDao
注解@Insert、@Delete、@Update、@Select用于修飾接口內(nèi)的方法(增刪改查)。

UserDao.java

package com.example.crud.mapper;

import com.example.crud.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
	/**
     * 查詢(xún)?nèi)繑?shù)據(jù)
     */
    @Select("select * from user")
    public List<User> findAll();
    
    **
     * 新增數(shù)據(jù)
     */
    @Insert("insert into user (username, password) values (#{username}, #{password})")
    public int save(User user);
    
	/**
     * 刪除數(shù)據(jù)
     */
	@Delete("delete from user where id=#{id}")
	public int delete(int id);

	/**
     * 根據(jù)ID查找用戶(hù)
     */
    @Select("select * from user where id=#{id}")
    public User get(int id);
    
    /**
     * 根據(jù)ID更新用戶(hù)數(shù)據(jù)
     */
     @Update("update user set username=#{username},password=#{password} where id=#{id}")
     public int updateById(User user);
     
}

Service

service下包含包impl和Service層的接口UserService
其中,包impl包含Service層接口的實(shí)現(xiàn)類(lèi)UserServiceImpl
Service層既需要調(diào)用Dao層接口,又需要提供接口給Controller層的類(lèi)進(jìn)行調(diào)用。

接口UserService.java

package com.example.crud.service;

import com.example.crud.pojo.User;

import java.util.List;

public interface UserService {
	/**
     * 查詢(xún)?nèi)繑?shù)據(jù)
     */
     public List<User> findAll();

	/**
     * 新增數(shù)據(jù)
     */
	public int save(User user);
	
	/**
     * 刪除數(shù)據(jù)
     */
    public int delete(int id);

    /**
     * 根據(jù)ID查找
     */
    public User get(int id);

    /**
     * 更新數(shù)據(jù)
     */
    public int updateById(User user);
    
}

接口實(shí)現(xiàn)類(lèi)UserServiceImpl.java

package com.example.crud.service.impl;

import com.example.crud.mapper.UserMapper;
import com.example.crud.pojo.User;
import com.example.crud.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 UserDao userDao;
	
	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}
	
	@Override
	public int save(User user) {
		return userDao.save(user);
	}

	@Override
	public int delete(int id) {
		return userDao.delete(id);
	}

	@Override
	public User get(int id) {
		return userDao.get(id);
	}

	@Override
	public int updateById(User user) {
		return userDao.updateById(user);
	}
	
}

Controller

controller包含類(lèi)UserControl
注解@Controller用于修飾類(lèi)UserControl
注解@Autowired表示自動(dòng)注入Service層提供的接口,供Controller層使用。

UserControl.java

package com.example.crud.controller;

import com.example.crud.pojo.User;
import com.example.crud.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;

@Controller
public class UserControl {
	
	@Autowired
	private UserService userservice;
	
	/**
	 * 查詢(xún)所有用戶(hù)數(shù)據(jù)
	 */
	@GetMapping("/index.html")
	public String userList(Map<String, List> result) {
		List<User> users = userService.findAll();
		result.put("users", users);
		return "index";
	}

	/**
     * 新增數(shù)據(jù)
     */
	@PostMapping("/add")
	public String save(User user) {
		userService.save(user);
		return "redirect:/index.html";
	}
	
	/**
     * 刪除數(shù)據(jù)
     */
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable int id, HttpServletResponse servletResponse) throws IOExceptioon {
		userService.delete(id);
		System.out.println("----delete方法執(zhí)行----");
		return "redirect:/index.html";
	}

	/**
	 * 根據(jù)id修改用戶(hù)數(shù)據(jù)
	 */
	 @GetMapping("/updatePage/{id}")
	 public String updatePage(Model model, @PathVariable int id) {
	 	User users = userService.get(id);
	 	model.addAttribute("users", users);
	 	return "modify";
	 }
	
	@PutMapping("/update")
	public String updateUser(Model model, User user, HttpServletRequest request) {
		String id = request.getParameter("id");
		User userById = userService.get(Integer.parseInt(id));
		userService.updataById(user);
		System.out.println(user);
		return "redirect:/index.html";
	}
	
}

前端頁(yè)面

resources下的包templates下有三個(gè)html文件。
?刪除按鈕添加了onclick="return confirm('確定刪除?')"防止誤操作。

主頁(yè)面index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用戶(hù)信息主頁(yè)面</title>
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<style>

    a{
        color: #ffffff;
    }
    h1{
        /*文字對(duì)齊*/
        text-align: center;
    }
    button{
        height: 50px;
        width: 50px;
        background-color: cornflowerblue;
    }
    .parent{
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .btn{
        width: auto;
    }

</style>

<body>
    <h1>Spring Boot增刪改查</h1>
    <!--table-striped:斑馬線(xiàn)格式,table-bordered:帶邊框,table-hover:鼠標(biāo)懸停高亮-->
    <table class="table table-striped table-bordered table-hover text-center">
        <thead>
            <tr style="text-align:center">
                <!--th標(biāo)簽定義html表格中的表頭單元格-->
                <th style="text-align:center">編號(hào)</th>
                <th style="text-align:center">用戶(hù)名</th>
                <th style="text-align:center">密碼</th>
                <th style="text-align:center">操作</th>
            </tr>
        </thead>
        <!--tr標(biāo)簽定義html表格中的所有行-->
        <!--遍歷集合,如果被遍歷的變量user為null或者不存在,則不會(huì)進(jìn)行遍歷,也不會(huì)報(bào)錯(cuò)-->
        <tr th:each="user:${users}">
            <!--td標(biāo)簽定義html表格中的標(biāo)準(zhǔn)單元格-->
            <td th:text="${user.id}"></td>
            <td th:text="${user.username}"></td>
            <td th:text="${user.password}"></td>
            <td>
                <!--a標(biāo)簽用來(lái)定義超鏈接 href表示超鏈接-->
                <a class="btn btn-primary" th:href="@{'/updatePage/'+${user.id}}">更改</a>
                <a class="btn btn-danger" th:href="@{'/delete/'+${user.id}}" onclick="return confirm('確定刪除?')">刪除</a>
            </td>
        </tr>
    </table>

    <div class="parent">
        <button type="button" class="btn btn-block"><a href="/add.html">添加用戶(hù)</a></button>
    </div>

</body>

</html>

添加用戶(hù)頁(yè)面add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用戶(hù)頁(yè)面</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<sty>

<body>
	<div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
	    <form action="/add" method="post">
	        <!--form-control給input添加這個(gè)class后就會(huì)使用bootstrap自帶的input框-->
	        用戶(hù)名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
	        <!--注意參數(shù)的拼接-->
	        密 碼:<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>

更改用戶(hù)信息界面modify.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>更改用戶(hù)信息界面</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:350px;margin-top: 180px;">
    <form action="/update" method="post">
        <!-- rest風(fēng)格中的更新是put請(qǐng)求,所以這塊先使用post請(qǐng)求,然后隱藏起來(lái)改為put請(qǐng)求-->
        <input name="_method" type="hidden" value="put">
        ID:<input class="form-control"  type="text" th:value="${user.id}" name="id"><br>
        用戶(hù)名:<input class="form-control" type="text" th:value="${user.username}" name="username"><br>
        密 碼:<input class="form-control" type="text" th:value="${user.password}" name="password"><br>
        <button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
    </form>
</div>

</body>
</html>

配置文件

application.yml

spring:
  web:
    resources:
      static-locations: classpath:/static/,classpath:/templates/
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/springboot_crud?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  mvc:
    hiddenmethod:
      filter:
        enabled: true
  devtools:
    restart:
      enabled: true # 設(shè)置開(kāi)啟熱部署
  freemarker:
    cache: false # 頁(yè)面不加載緩存,修改即使生效
mybatis:
  configuration:
    map-underscore-to-camel-case: true # 下劃線(xiàn)駝峰設(shè)置
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   # 打印SQL語(yǔ)句

運(yùn)行

在chrome瀏覽器中輸入http://localhost:8080/index.html,即可進(jìn)入用戶(hù)信息主頁(yè)面。

原文鏈接:https://blog.csdn.net/hutianle/article/details/125783304

欄目分類(lèi)
最近更新