根据springboot项目基础整合mybatis

因为有作业,所以我很“情愿”的就写完了这个项目,只为了学习知识,绝不是为了交作业,绝不是。

首先是导入依赖的问题

需要的依赖:Lombok、Spring Web、Themleaf、MySQL Driver、MyBatis Framework。
在这里插入图片描述

实体类中需要用到的注释

@Data:导入getter()、setter()方法
@AllArgsConstructor:导入全参构造
@NoArgsConstructor:导入无参构造

一、图书信息的管理(CRUD)

1.Mapper层(也就是Dao层)

import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface LibraryMapper {
    // 添加图书
    boolean AddBook(Library library);
    // 图书查询(包括单条件查询,多条件查询,全条件查询)
    List<Library> QueryBook(Library library);
    // 删除图书信息
    @Delete("Delete from book where id = #{id}")
    int deleteBook(Integer id);
    // 更新图书信息
    @Update("update book set name = #{name},price=#{price} where id=#{id}")
    int updateBook(Integer id);
}

2.Mapper.xml

通过配置文件进行CRUD操作,也可以使用注解。
LibraryMapper.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="nuc.edu.mapper.LibraryMapper">

    <insert id="AddBook" parameterType="nuc.edu.entity.Library" >
        insert into book (id, name, price) values (#{id}, #{name}, #{price})
    </insert>

    <select id="QueryBook" parameterType="nuc.edu.entity.Library" resultType="nuc.edu.entity.Library">
        select * from book
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="price != null">
                and price = #{price}
            </if>
        </where>
    </select>
</mapper>

3.Controller层

控制层,实现业务调度
LibController

package nuc.edu.controller;

import nuc.edu.entity.Library;
import nuc.edu.service.LibService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class LibController {

    @Autowired
    private  LibService libService;
    @GetMapping("/addbook")
    public String AddBook(@RequestParam(value = "id",required = false ) Integer id,
                          @RequestParam(value = "name",required = false) String name,
                          @RequestParam(value = "price",required = false) Integer price,
                          Model model){
        if("".equals(id)){
            id = null;
        }
        if ("".equals(price)){
            price = null;
        }
        libService.AddBook(new Library(id, name, price));
        //model.addAttribute("libraries",bookList);
        return "redirect:/library";
    }

    @GetMapping ("/library")
    public String QueryBook(@RequestParam(value = "id",required = false) Integer id,
                            @RequestParam(value = "name",required = false) String name,
                            @RequestParam(value = "price",required = false) Integer price,
                            Model model){
        if (name != ""){
            name = null;
        }
        Library library = new Library(id, name, price);
        List<Library> libraryList = libService.QueryBook(library);
        model.addAttribute("libraries",libraryList);
        return "index";
    }

    @GetMapping("/toadd")
    public String ToAddBook(){
        return "addbook";
    }

    @GetMapping("/deletebook/{id}")
    public String deleteBook(@PathVariable Integer id){
        libService.deleteBook(id);
        return "index";
    }

    @GetMapping("/updateBook")
    public String updateBook(@RequestParam(value = "id",required = false) Integer id,
                             @RequestParam(value = "name",required = false) String name,
                             @RequestParam(value = "price",required = false) Integer price){
        libService.updateBook(new Library(id,name,price));
        return "redirect:/library";
    }

    @GetMapping("/toupdate/{id}/{name}/{price}")
    public String toupdate(@PathVariable Integer id,
                           @PathVariable String name,
                           @PathVariable Integer price,
                           Model model){
        System.out.println(id);
        Library library = new Library(id,name,price);
        model.addAttribute("library",library);
        return "update";
    }
}


4.前端页面

(1)主界面
index
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/library" method="get">
    图书编号ID
    <input name="id" type="text">
    图书名称Name
    <input name="name" type="text">
    价格Price
    <input name="price" type="text">
    <input value="查询(默认为查询全部)" type="submit"></input>
    <input value="新增书籍" type="button" onclick="a1()">

</form>
<button onclick="a2()">上传文件</button>

<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Price</th>
    </tr>

    </tr>
    <tr th:each="library : ${libraries}">
        <td th:text="${library.id}"></td>
        <td th:text="${library.name}"></td>
        <td th:text="${library.price}"></td>
        <td>
            <form method="get">
                <input value="删除" type="submit" th:formaction="@{/deletebook/}+${library.id}">
                <input value="编辑" type="submit" th:formaction="@{/toupdate/}+${library.id}+'/'+${library.name}+'/'+${library.price} ">
            </form>
        </td>
    </tr>
</table>

<script>
    function a1(){
        window.location.href = "/toadd";
    }
    function a2(){
        window.location.href = "/upload";
    }
</script>

</body>
</html>
(2)图书添加界面
addbook
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加图书</title>
</head>
<body>
<form action="/addbook" method="get">
    图书编号ID
    <input name="id" type="text">
    图书名称Name
    <input name="name" type="text">
    价格Price
    <input name="price" type="text">
    <input value="添加" type="submit"></input>
</form>
</body>
</html>
(3)图书更新界面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>更新界面</title>
</head>
<body>
<form action="/updateBook">
    <table>
        图书ID
        <input name="id" type="text" th:value="${library.id}" readonly="readonly">
        图书名称Name
        <input name="name" type="text" th:value="${library.name}">
        价格Price
        <input name="price" type="text" th:value="${library.price}">
        <input type="submit" value="更新">
    </table>
</form>
</body>
</html>

二、文件上传

1.Controller层

FileController
package nuc.edu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileController {
    @GetMapping("/upload")
    public String uploadPage(){
        return "upload";
    }

    @PostMapping("upload")
    public Map<String, Object> upload(@RequestBody MultipartFile photo){
        String path = "D:\\IDEA\\IDEA-workspace\\MyBatis\\src\\main\\resources\\static\\img\\";//保存路径
        String filename = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
        if (!suffix.equals(".jpg")){
            return dealResultMap(false,"上传失败");
        }
        try{
            FileCopyUtils.copy(photo.getInputStream(), new FileOutputStream(path + filename +suffix));
        } catch (IOException e){
            e.printStackTrace();
            return dealResultMap(false,"上传失败");
        }
        return dealResultMap(true,"上传成功");
    }
    private Map<String, Object> dealResultMap(boolean success, String msg){
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", success);
        result.put("msg", msg);
        return result;
    }
}

2.前端页面

upload
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="photo" value="请选择上传的文件" />
    <input type="submit" value="提交" />
    <input type="button" value="返回" onclick='window.open("/library")'>
</form>
</body>
</html>

三、登录管理

1.前端界面

(1)登录界面(包括用户与管理员)

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="/checklogin" method="get">
    用户登录
    <br>
    账号:
    <input name="username" type="text">
    <br>
    密码:
    <input name="password" type="text">
    <br>
    <input value="登录" type="submit">
    <input value="注册" type="button" onclick='location.href="/toregister"'>
    <input value="进入管理员登录" type="submit" formaction="/adminLogin">

    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

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

adminLogin.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理员登录</title>
</head>
<body>
<form action="/checkAdminLogin" method="get">
  用户登录
  <br>
  账号:
  <input name="name" type="text">
  <br>
  密码:
  <input name="password" type="text">
  <br>
  <input value="管理员登录" type="submit">
  <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
</form>
</body>
</html>
(2)用户注册界面

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<form action="/register" method="get">
    请输入注册信息:
    <br>
    用户名:
    <input name="name" type="text">
    密码:
    <input name="password" type="text">
    <input value="注册" type="submit">
</form>
</body>
</html>
(3)Controller层
LoginController
package nuc.edu.controller;

import nuc.edu.entity.Admin;
import nuc.edu.entity.User;
import nuc.edu.mapper.AdminMapper;
import nuc.edu.service.AdminService;
import nuc.edu.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.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/checklogin")
    public String login(@RequestParam(value = "username",required = false ) String username,
                        @RequestParam(value = "password",required = false) String password,
                        Model model,
                        HttpSession session){
        User user = userService.QueryUser(new User(username,password));
        if (user!=null){
            session.setAttribute("LoginUser",username);
            return "redirect:/ulibrary";
        }else {
            model.addAttribute("msg","用户名或密码错误!");
            return "login";
        }
    }

    @GetMapping("/adminLogin")
    public String toAdminLogin(){
        return "adminLogin";
    }
    @GetMapping("/checkAdminLogin")
    public String adminLogin(@RequestParam(value = "name",required = false ) String name,
                             @RequestParam(value = "password",required = false) String password,
                             Model model,
                             HttpSession session){
        Admin admin = adminService.Queryadmin(new Admin(name,password));
        if (admin != null){
            session.setAttribute("LoginUser",name);
            return "redirect:/library";
        }else {
            model.addAttribute("msg","用户名或密码错误!");
            return "adminLogin";
        }
    }

    @GetMapping("/toregister")
    public String toregister(){
        return "register";
    }
    @GetMapping("/register")
    public String registerUser(@RequestParam(value = "name",required = false) String name,
                               @RequestParam(value = "password", required = false) String password){
        userService.AddUser(new User(name,password));
        return "redirect:/login";
    }
}

四、总结

放一张某位大佬给讲的图,debug很有用。直接上图
请添加图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值