SpringBoot + Thymeleaf实现CRUD操作

一、效果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二、后端代码

(1)数据模拟

package com.ityj.util;

import com.ityj.entity.CobEntity;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CobStaticData {

    public static List<CobEntity> cobData = initData();

    private static List<CobEntity> initData() {
        List<CobEntity> cobList = new ArrayList<>();
        CobEntity entity = new CobEntity("斗鱼", "https://www.douyu.com/99999");
        CobEntity entity2 = new CobEntity("优快云", "https://blog.youkuaiyun.com/");
        cobList.add(entity);
        cobList.add(entity2);
        return cobList;
    }

    public static void addCob(CobEntity cobEntity) {
        if (ObjectUtils.isEmpty(cobEntity)) {
            return;
        }
        Iterator<CobEntity> iterator = cobData.iterator();
        while(iterator.hasNext()) {
            CobEntity entity = iterator.next();
            String cob = entity.getCob();
            if (cobEntity.getCob().equals(cob)) {
                System.out.println("添加失败,已经存在!");
                return;
            }
        }
        cobData.add(cobEntity);


    }

    public static void removeCob(String cob) {
        Iterator<CobEntity> iterator = cobData.iterator();
        while(iterator.hasNext()) {
            CobEntity entity = iterator.next();
            String entityCob = entity.getCob();
            if (cob.equals(entityCob)) {
                iterator.remove();
                break;
            }
        }
        System.out.println("删除后 list : " + cobData);
    }

    public static void updateCob(String cob, String url) {
        // 默认cob是key,不可修改
        if (ObjectUtils.isEmpty(cob) || ObjectUtils.isEmpty(url)) {
            return;
        }
        Iterator<CobEntity> iterator = cobData.iterator();
        while(iterator.hasNext()) {
            CobEntity entity = iterator.next();
            String entityCob = entity.getCob();
            if (cob.equals(entityCob)) {
                entity.setUrl(url);
                break;
            }
        }
    }
}

(2)实体类

package com.ityj.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class CobEntity {
    private String cob;
    private String url;
}

(2)控制器controller

package com.ityj.controller;

import com.ityj.util.CobStaticData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@Slf4j
public class IndexController {

    @GetMapping(path = {"/toIndex", "/", ""})
    public ModelAndView toIndex() {
        log.info("get into toIndex()...");
        ModelAndView mv = new ModelAndView();
        mv.addObject("codAndUrlList", CobStaticData.cobData);
        mv.setViewName("index");
        return mv;
    }

}

package com.ityj.controller;

import com.ityj.entity.CobEntity;
import com.ityj.util.CobStaticData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Slf4j
public class CobController {

    @GetMapping(path = "/toCobList")
    public ModelAndView toCobList() {
        log.info("get into toCobList...");
        ModelAndView mv = new ModelAndView();
        mv.addObject("codAndUrlList", CobStaticData.cobData);
        mv.setViewName("cob/list");
        return mv;
    }

    @GetMapping(path = "/toAdd")
    public String toAddPage() {
        log.info("get into toAddPage...");
        return "cob/cobAdd";
    }

    @GetMapping(path = "/toEdit")
    public ModelAndView toEditPage(@RequestParam("cob") String cob,
                             @RequestParam("url") String url) {
        log.info("get into toEditPage...");
        ModelAndView mv = new ModelAndView();
        mv.addObject("cob", cob);
        mv.addObject("url", url);
        mv.setViewName("cob/cobEdit");
        return mv;
    }

    @PostMapping(path = "/addCobInfo")
    public String addCobInfo(CobEntity cobEntity) {
        log.info("get into addCobInfo... input param : " + cobEntity);
        CobStaticData.addCob(cobEntity);
        return "redirect:toCobList";
    }

    @GetMapping(path = "/deleteCobInfo")
    public String deleteCobInfo(@RequestParam("cob") String cob) {
        log.info("get into deleteCobInfo... input param : " + cob);
        CobStaticData.removeCob(cob);
        return "redirect:toCobList";
    }

    @PostMapping(path = "/updateCobInfo")
    public String deleteCobInfo(@RequestParam("cob") String cob,
                                @RequestParam("url") String url) {
        log.info("get into deleteCobInfo... input param={},url={}", cob, url);
        CobStaticData.updateCob(cob, url);
        return "redirect:toCobList";
    }
}

三、配置文件


spring:
  thymeleaf:
    cache: false
server:
  port: 8081
  servlet:
    context-path: /frame

四、前端页面代码

在这里插入图片描述
(1)引入bootstrap和jquery
(2)首页展示

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF‐8">
    <title>Index</title>
    <script th:src="@{webjars/jquery/3.3.1/jquery.min.js}"></script>
    <script>

      $(function () {
        changeUrl();
      })
      function changeUrl() {
        var tempValue = $("#codSelect option:selected").attr("temp");
        $("#iframeId").attr("src", tempValue);
      }
    </script>
  </head>

  <body>
    <h1>Welcome</h1>

    <div>
      <form>
        <span>请选择:</span>
        <select id="codSelect" th:onchange="changeUrl()">
          <option th:each="cobEntity : ${codAndUrlList}" th:value="${cobEntity.cob}" th:text="${cobEntity.cob}"  th:temp="${cobEntity.url}"></option>
        </select>
      </form>
    </div>

    <br/>

    <iframe id="iframeId" src="https://mybatis.org/mybatis-3/zh/getting-started.html" style="position: relative; width: 100%; height: 600px"></iframe>

  </body>
</html>

(3)增删改查
list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>cobList列表</title>
        <!--thymeleaf表达式,th:href="@{/css/bootstrap.css}"@表示后面的是一个链接-->
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
    </head>

    <body class="container">
        <h1>cobList列表</h1>
        <br/><br/>
        <div class="with:80%">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>#</th>
                    <th>Cob</th>
                    <th>url</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
                </thead>
                <tbody>
                <!--each来进行for循环求值-->
                <tr th:each="cobEntity,rowStat : ${codAndUrlList}">
                    <th scope="row" th:text="${rowStat.count}">1</th>
                    <td th:text="${cobEntity.cob}">cob</td>
                    <td th:text="${cobEntity.url}">url</td>
                    <td><a th:href="@{/toEdit(cob=${cobEntity.cob},url=${cobEntity.url})}">edit</a></td>
                    <td><a th:href="@{/deleteCobInfo(cob=${cobEntity.cob})}">delete</a></td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="form-group">
            <div class="col-sm-2 control-label">
                <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
            </div>
        </div>

    </body>
</html>

cobAdd.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>cobAdd</title>
        <!--利用thymeleaf表达式获取css路径,bootstrap给button提供样式-->
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
    </head>

    <body class="container">
    <h1>添加cobAdd信息</h1>
    <br/><br/>

    <div class="with:80%">
        <form class="form-horizontal"  th:action="@{/addCobInfo}"  method="post">
            <div class="form-group">
                <label for="cob" class="col-sm-2 control-label">cob</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="cob"  id="cob" placeholder="cob"/>
                </div>
            </div>
            <div class="form-group">
                <label for="url" class="col-sm-2 control-label" >url</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="url" id="url" placeholder="url"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info" />
                    <input type="reset" value="Reset" class="btn btn-info" />
                </div>
            </div>
        </form>
    </div>
    </body>
</html>

cobEdit.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>edit Cob</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
    </head>
    <body class="container">
        <h1>修改cob信息</h1>
        <br/><br/>
        <div class="with:80%">
            <form class="form-horizontal"   th:action="@{/updateCobInfo}" method="post">
                <div class="form-group">
                    <label for="cob" class="col-sm-2 control-label">cob</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="cob"  id="cob" th:value="${cob}" placeholder="cob"/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="url" class="col-sm-2 control-label" >url</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="url" id="url"  th:value="${url}" placeholder="url"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input type="submit" value="Submit" class="btn btn-info" />
                        <a href="/toAdd" th:href="@{/toCobList}" class="btn btn-info">Back</a>
                    </div>

                </div>
            </form>
        </div>
    </body>
</html>

五、Swagger的整合

1、pom

		<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.1</version>
        </dependency>

2、配置类

package com.ityj.yygh.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {

    // http://localhost:8081[prot/contextpath]/doc.html
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)  // 控制是否生效,可以通过配置文件,对生产环境的swagger进行排除
                .select()       // 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.ityj"))
                .build();
    }

    /**
     * 自定义配置文档信息
     *
     * @return
     */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("Jack", "1272097458", "1272097458@qq.com");
        return new ApiInfo(
                "SpringCloud",            // 文档大标题
                "尚医通springcloud学习项目",                          // 描述
                "2021年5月12日22:49:37",                 //版本
                "https://mp.youkuaiyun.com/console/article",   // 组织链接
                contact,                                       // 联系人信息
                "Apache 2.0",                           // 许可
                "许可链接",                           // 许可链接
                new ArrayList()                                 // 扩展
        );
    }

}

3、调用链接
http://localhost:8201/doc.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值