springboot2.0+mybatis整合freemarker(增删改查)

前言

thymeleaf和freemarker比较,个人更倾向于freemarker这种模板引擎,两者的设计思路本就不同。

springboot整合freemarker

引入依赖

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

配置application.yml

spring:
  freemarker:
    suffix: .ftl
    template-loader-path: classpath:/templates
  datasource:
    url: jdbc:mysql://88.88.88.194:3306/master1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

server:
  port: 8080
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.orm.mybatis.freemarker.entity
  configuration:
    map-underscore-to-camel-case: true

Spring boot2.0访问静态资源就会被同步拦截。

需要创建一个类名为AWebMvcConfigurer 继承WebMvcConfigurer
我们使用的Springboot本身把静态资源目录设置为"/",所以我们访问静态资源时是不需要加上/static的,因此在放行拦截的使用不能使用/static/**.因此我在/下创建目录res放入我全部的静态资源,并以此目录放行。

//配置拦截事件
@Configuration
public class AWebMvcConfigurer implements WebMvcConfigurer {


//    静态资源映射,保证资源的正确访问
//    重写上述方法可以达到拦截器的效果,但是在使用FreeMarker时有时会导致不能加载css、js文件。
//    在上述创建类中重写
//    这时我们需要重写映射文件类即public void addResourceHandlers(ResourceHandlerRegistry registry) 类

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/res/**")
                .addResourceLocations("classpath:/res/");
        registry.addResourceHandler("/templates/**")
                .addResourceLocations("classpath:/templates/");
    }
}

三个页面

index.ftl 页面

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="../res/bootstrap-4.5.0-dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="../res/font-awesome-4.7.0/css/font-awesome.min.css">
    </head>

    <body>
    <div class="container">
	     <div class="panel panel-primary">
			  <div class="panel-heading">
			    <h2>Home Page</h2>
			  </div>
	        <a href="showUsers">Show User (Retrieve employee data from database)</a>
             <p></p>
	        <a href="table">Show User CRUD</a>
	        </div>
        </div>
    </body>

</html>

showUsers.ftl

<!DOCTYPE html>
<html>
    <head>
        <title>Employee List</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
		<script src="../res/jquery-3.5.1.min.js"></script>
        <link rel="stylesheet" href="css/style.css">
        </head>
    <body>
    <div class="container">
       <div class="panel panel-primary">
		  <div class="panel-heading">
		    <h2>User List</h2>
		  </div>
		  <div class="panel-body">
            
		    <table class="table table-striped">
		      <thead>
		        <tr>
		          <th>Id</th>
		          <th>Num</th>
		          <th>Name</th>
		          <th>Address</th>
		          <th>Abc</th>
		        </tr>
		      </thead>
		      <tbody>
		       <#list userList as user>
                <tr>
                    <td>${user.id}</td>
                    <td>${user.num}</td>
                    <td>${user.name}</td>
                    <td>${user.address!"null"}</td>
                    <td>${user.ABC!"null"}</td>
                </tr>
			   </#list>
		      </tbody>
		    </table>
		  </div>
		</div>
		</div>
     </body>
</html>

table.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据表格</title>
    <link rel="stylesheet" href="../res/bootstrap-4.5.0-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../res/font-awesome-4.7.0/css/font-awesome.min.css">
    <script src="../res/jquery-3.5.1.min.js"></script>
    <script src="../res/popper.min.js"></script>
    <script src="../res/bootstrap-4.5.0-dist/js/bootstrap.min.js"></script>
    <script src="../res/layer/layer.js"></script>
    <style>
        .form-text {
            width: 100px;
            text-align: center;
        }
    </style>
</head>
<body>
&nbsp;&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-primary" id="btn_add"><i class="fa fa-plus-square" aria-hidden="true"></i>&nbsp;添加
</button>
&nbsp;&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-primary" id="btn_del"><i class="fa fa-trash" aria-hidden="true"></i>&nbsp;删除
</button>
&nbsp;&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-primary" id="btn_edit"><i class="fa fa-pencil-square" aria-hidden="true"></i>&nbsp;修改
</button>
&nbsp;&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-primary" id="btn_info"><i class="fa fa-info-circle" aria-hidden="true"></i>&nbsp;查看
</button>

<table class="table table-hover table-bordered">
    <thead class="thead-light">
    <tr align="center">
        <th><input type="checkbox" id="isAll"></th>
<#--        <th>Id</th>-->
        <th>Num</th>
        <th>Name</th>
        <th>Address</th>
        <th>Abc</th>
    </tr>
    </thead>
    <tbody>
    <#list userList as user>
        <tr align="center">
            <td><input type="checkbox" name="id" class="form-check" value="${user.id}"></td>
            <td>${user.num!"null"}</td>
            <td>${user.name!"null"}</td>
            <td>${user.address!"null"}</td>
            <td>${user.ABC!"null"}</td>
        </tr>
    </#list>
    <div class="form-group"  style="margin-top: 10px;margin-left: 20px">
        <label for="num">id</label>
        <input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_id"  type="text" placeholder=""
               name="num"
               value=""
               autocomplete="off">
        <label for="num">num</label>
        <input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_num"  type="text" placeholder=""
               name="num"
               value=""
               autocomplete="off">
        <label for="name">Name</label>
        <input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_name"  type="text" placeholder=""
               name="name"
               value="" autocomplete="off">
        <label for="address">address</label>
        <input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_address"  type="text" placeholder=""
               name="address"
               value="" autocomplete="off">
        <label for="aBC">abc</label>
        <input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_aBC"  type="text" placeholder=""
               name="aBC"
               value="" autocomplete="off">
        <button class="btn btn-primary" id="btn_andrew" style="margin-bottom: 5px">确认修改</button>

    </div>

    </tbody>
</table>
<!-- 新增员工模态框 -->
<div id="addModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <button class="close" data-dismiss="modal">
                    <span>×</span>
                </button>
            </div>
            <div class="modal-title">
                <h1 class="text-center">用户信息</h1>
            </div>
            <div class="modal-body">
                <form class="form-group" action="">
                    <div class="form-group">
                        <label for="num">num</label>
                        <input class="form-control form-add" id="num" type="text" placeholder="" name="num"
                               value=""
                               autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="name">name</label>
                        <input class="form-control form-add" id="name" type="text" placeholder="" name="name"
                               value="" autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="address">address</label>
                        <input class="form-control form-add" id="address" type="text" placeholder="" name="address"
                               value="" autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="aBC">abc</label>
                        <input class="form-control form-add" id="aBC" type="text" placeholder="" name="aBC"
                               value="" autocomplete="off">
                    </div>
                    <div class="text-right">
                        <button class="btn btn-primary" id="add_submit" type="submit">提交</button>
                        <button class="btn btn-danger" data-dismiss="modal">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- 员工信息模态框 -->
<div id="infoModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <button class="close" data-dismiss="modal">
                    <span>×</span>
                </button>
            </div>
            <div class="modal-title">
                <h1 class="text-center">用户信息</h1>
            </div>
            <div class="modal-body">
                <form class="form-group" action="">
                    <div class="form-group">
                        <label for="num">num</label>
                        <input class="form-control form-edit" id="info_num" readonly type="text" placeholder=""
                               name="num"
                               value=""
                               autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="num">Name</label>
                        <input class="form-control form-edit" id="info_name" readonly type="text" placeholder=""
                               name="name"
                               value="" autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="address">address</label>
                        <input class="form-control form-edit" id="info_address" readonly type="text" placeholder=""
                               name="address"
                               value="" autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="aBC">abc</label>
                        <input class="form-control form-edit" id="info_aBC" readonly type="text" placeholder=""
                               name="aBC"
                               value="" autocomplete="off">
                    </div>
                    <div class="text-right">
                        <button class="btn btn-danger" data-dismiss="modal">关闭</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>
<script>
    $(function (e) {
        $('#addModal').on('show.bs.modal', function (e) {
            var $this = $(this);
            var $modal_dialog = $this.find('.modal-dialog');
            $this.css('display', 'block');
            $modal_dialog.css({'margin-top': Math.max(0, ($(window).height() - $modal_dialog.height()) / 2 - 30)});

        });
        var addOrSave = true;
        $('#btn_add').on('click', function (e) {
            e.preventDefault();
            addOrSave = true;
            $("#addModal").modal({backdrop: true, keyboard: true});
        });
        $('#add_submit').on('click', function (e) {
            e.preventDefault();
            let data = {};
            let forms = $('.form-add');
            $.each(forms, function(index, input){
                data[input.name] = input.value;
            });
            // data.test = ["3","5",{"a":"asd"}];
            if(!addOrSave){
                let list = sessionStorage.getItem('ids');
                data['ids'] = JSON.parse(list);
            }
            window.console.log(data);
            let methodName = addOrSave ? 'add' : 'edit';
            $.ajax({
                method: "post",
                url: '/user/' + methodName,
                async: false,
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (respose) {
                    switch (respose.code) {
                        case "200": {
                            window.location.replace("/user/table");
                            break;
                        }
                    }
                }
            });
        });
        $('#btn_andrew').on('click', function (e) {
            e.preventDefault();
            let data = {};
            let list = [];
            // data[input.name] = input.value;
            // data.test = ["3","5",{"a":"asd"}];
            if ($('#andrew_id')[0].value){
                console.log("1")
                addOrSave = false;
            }else {
                console.log("2")
                addOrSave = true;
            }
            list.push($('#andrew_id')[0].value)
            data.ids = [...list];
            data.num = $('#andrew_num')[0].value;
            data.name = $('#andrew_name')[0].value;
            data.address = $('#andrew_address')[0].value;
            data.aBC = $('#andrew_aBC')[0].value;

            window.console.log(data);
            let methodName = addOrSave ? 'add' : 'edit';
            $.ajax({
                method: "post",
                url: '/user/' + methodName,
                async: false,
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (respose) {
                    switch (respose.code) {
                        case "200": {
                            window.location.replace("/user/table");
                            break;
                        }
                    }
                }
            });
        });
        $('#isAll').change(function (e) {
            if ($('#isAll').is(':checked')) {
                $('.form-check').each(function (index, element) {
                    if (!element.checked) {
                        element.checked = true;
                    }
                });
            } else {
                $('.form-check').each(function (index, element) {
                    if (element.checked) {
                        element.checked = false;
                    }
                });
            }
        });
        $('.form-check').click(function (e) {
            e.preventDefault();
        });
        $('tr').slice(1).click(function (e) {
            // let checkbox = $("input[type='checkbox']",this)[0];
            let checkbox = $("input:checkbox", this)[0];
            if (checkbox.checked) {
                checkbox.checked = false;
            } else {
                checkbox.checked = true;
            }
            check($('.form-check'));
        })

        function check(items) {
            let flag = true;
            $(items).each(function (index, element) {
                if (!element.checked) {
                    flag = false;
                }
            });
            let isAll = window.document.querySelector(`#isAll`)
            isAll.checked = flag;
        }

        $('#btn_del').click(function (e) {
            e.preventDefault();
            let list = new Array();
            $('.form-check').each(function (index, element) {
                if (element.checked) {
                    list.push(element.value);
                }
            });
            if (list.length > 0) {
                $.ajax({
                    method: "post",
                    url: '/user/delete',
                    async: false,
                    data: JSON.stringify({"ids": JSON.parse(JSON.stringify(list))}),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (respose) {
                        switch (respose.code) {
                            case "200": {
                                window.location.replace("/user/table");
                                break;
                            }
                        }
                    }
                });
            } else {
                layer.msg('请选择要删除的员工', {icon: 2});
            }
        });
        $('#btn_info').click(function (e) {
            e.preventDefault();
            let list = new Array();
            $('.form-check').each(function (index, element) {
                if (element.checked) {
                    list.push(element.value);
                }
            });
            if (list.length > 0) {
                $.ajax({
                    method: "post",
                    url: '/user/getUserById',
                    async: false,
                    data: JSON.stringify({"ids":[...list]}),
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (respose) {
                        console.log(respose.code);
                        switch (respose.code) {
                            case "200": {
                                $("#infoModal").modal({backdrop: true, keyboard: true});
                                $('#info_num').val(respose.data.num);
                                $('#info_address').val(respose.data.address);
                                $('#info_aBC').val(respose.data.aBC);
                                $('#info_name').val(respose.data.name);
                                break;
                            }
                        }
                    }
                });
            } else {
                layer.msg('请选择要查看的员工', {icon: 2});
            }
        });
        $('#btn_edit').click(function(e){
            e.preventDefault();
            addOrSave = false;
            let list = new Array();
            $('.form-check').each(function (index, element) {
                if (element.checked) {
                    list.push(element.value);
                }
            });
            sessionStorage.setItem('ids',JSON.stringify(list));
            if (list.length > 0) {
                $.ajax({
                    method: "post",
                    url: '/user/getUserById',
                    async: false,
                    data: JSON.stringify({'ids':JSON.parse(JSON.stringify(list))}),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (respose) {
                        console.log(respose.code);
                        switch (respose.code) {
                            case "200": {
                                $("#addModal").modal({backdrop: true, keyboard: true});
                                $('#num').val(respose.data.num);
                                $('#address').val(respose.data.address);
                                $('#aBC').val(respose.data.aBC);
                                $('#name').val(respose.data.name);
                                break;
                            }
                        }
                    }
                });
            } else {
                layer.msg('请选择要查看的员工', {icon: 2});
            }
        });
    });
</script>

控制层

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2022-03-11 09:53:09
 */
@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserServiceImpl userService;

    @GetMapping("/")
    public String index(Model model) {
        return "index";
    }

    @GetMapping("/test")
    public String test(Model model) {
        return "index";
    }

    @GetMapping("/showUsers")
    public ModelAndView showCities() {

        List<User> userList = userService.queryAll();

        Map<String, Object> params = new HashMap<>();

        System.out.println(userList.toString());

        params.put("userList", userList);

        return new ModelAndView("showUsers", params);

    }

    @GetMapping("/table")
    public ModelAndView showUser() {

        List<User> userList = userService.queryAll();

        Map<String, Object> params = new HashMap<>();

        System.out.println(userList.toString());

        params.put("userList", userList);

        return new ModelAndView("table", params);

    }

    @ResponseBody
    @PostMapping(value = "/getUserById",produces = {"application/json;charset=UTF-8"}  )
    public Object getUserById(@RequestBody String json) {
        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String temp = jsonObject.getString("ids");
        List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
        Integer id = Integer.valueOf(ids.get(0));
        User user1 = userService.queryById(id);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("data",user1);
        jsonObject1.put("code","200");
        return jsonObject1;
    }

    @ResponseBody
    @PostMapping(value = "/edit",produces = {"application/json;charset=UTF-8"}  )
    public Object editUserById(@RequestBody String json) {
        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String temp = jsonObject.getString("ids");
        List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
//        String[] ids = temp.split(",");
//        List<String> list = Arrays.asList(ids);
//        Integer id = Integer.valueOf(list.get(0));
        System.out.println(ids);
        System.out.println(ids.get(0));
        User user1 = User.builder().id(ids.get(0))
                .num(Integer.valueOf((String)jsonObject.get("num")))
                .address((String) jsonObject.get("address"))
                .name((String) jsonObject.get("name"))
                .aBC(jsonObject.getString("aBC"))
                .build();
        userService.update(user1);
        JSONObject jsonObject1 = new JSONObject();

        jsonObject1.put("code","200");
        return jsonObject1;
    }

    @ResponseBody
    @PostMapping(value = "/add",produces = {"application/json;charset=UTF-8"}  )
    public Object addUserById(@RequestBody String json) {
        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String temp = jsonObject.getString("ids");
        List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
//        String[] ids = temp.split(",");
//        List<String> list = Arrays.asList(ids);
//        Integer id = Integer.valueOf(list.get(0));
//        System.out.println(ids);
//        System.out.println(ids.get(0));
        User user1 = User.builder()
                .num(Integer.valueOf((String)jsonObject.get("num")))
                .address((String) jsonObject.get("address"))
                .name((String) jsonObject.get("name"))
                .aBC(jsonObject.getString("aBC"))
                .build();
        userService.insert(user1);
        JSONObject jsonObject1 = new JSONObject();

        jsonObject1.put("code","200");
        return jsonObject1;
    }

    @ResponseBody
    @PostMapping(value = "/delete",produces = {"application/json;charset=UTF-8"}  )
    public Object deleteUserById(@RequestBody String json) {
        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String temp = jsonObject.getString("ids");
        List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
        ids.forEach(
                (v)-> userService.deleteById(v)
        );

        JSONObject jsonObject1 = new JSONObject();

        jsonObject1.put("code","200");
        return jsonObject1;
    }

}

测试

在这里插入图片描述

结果能实现跳转和增删改查

项目地址

https://gitee.com/liuweiqiang12/springboot


如果这篇文章对您有帮助,可否支持一下博主?
点赞+关注呗,谢谢您。

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用Spring Boot,MyBatis和Vue进行增删操作的步骤如下: 1. 设置Spring Boot项目: - 使用Spring Initializr创建一个新的Spring Boot项目。 - 在pom.xml文件中添加所需的依赖项,包括Spring Boot、MyBatis和Vue相关的依赖项。 - 配置数据库连接信息,例如数据库URL、用户名和密码等。 2. 创建数据库表: - 使用SQL脚本或图形化工具创建数据库表,定义表结构和字段。 3. 创建实体类: - 在Spring Boot项目中创建Java实体类,代表数据库表中的每个字段。 - 使用注解(如@TableName)映射实体类和数据库表。 4. 创建Mapper接口: - 在Spring Boot项目中创建Mapper接口,用于定义数据库的增删操作。 - 使用MyBatis的注解(如@Select、@Insert、@Update、@Delete)映射接口方法和SQL询。 5. 实现Mapper接口: - 在Spring Boot项目中创建Mapper接口的实现类,实现具体的数据操作逻辑。 6. 创建Vue前端页面: - 在Vue项目中创建前端页面,用于展示数据和接收用户的输入。 - 使用Vue的模板语法和组件库构建用户界面。 7. 发送HTTP请求: - 在Vue前端页面中,使用axios或其他HTTP库发送HTTP请求到Spring Boot后端服务器的API接口。 - 根据需求,发送对应的增删请求(如GET请求询数据,POST请求添加数据,PUT请求更新数据,DELETE请求删除数据)。 8. 处理API请求: - 在Spring Boot项目中,处理来自Vue前端页面的API请求。 - 解析请求参数,调用对应的Mapper接口方法,进行增删操作。 - 将操作结果封装成JSON格式,返回给前端页面。 通过以上步骤,你可以实现使用Spring Boot、MyBatis和Vue进行增删操作的应用程序。这些步骤提供了一个基本的指导,你可以根据具体的需求进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

叶孤崖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值