1. 程式人生 > 其它 >SpringBoot整合MyBatis-Plus+Thymeleaf+攔截器

SpringBoot整合MyBatis-Plus+Thymeleaf+攔截器

技術標籤:企業級框架springspring bootmybatis

為熱愛程式設計的你點贊!
學習SpringBoot實戰課程 https://edu.csdn.net/course/detail/31433
學習SpringCloud入門課程 https://edu.csdn.net/course/detail/31451


前言

本文帶大家開發一個SpringBoot案例,掌握SpringBoot整合MyBatis-Plus、SpringMVC、Thymeleaf以及攔截器的應用開發技能。

案例介紹

案例包含登入和書籍列表顯示兩個功能:
登入頁面
在這裡插入圖片描述
登入失敗
在這裡插入圖片描述
登入成功看到書籍列表
在這裡插入圖片描述
資料庫包含兩張表:

tb_user使用者表
在這裡插入圖片描述
tb_book書籍表
在這裡插入圖片描述

整合MyBatis-Plus

MyBatis-Plus是MyBatis的增強框架,提供了通用的Mapper和Service介面
匯入依賴

<dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <optional>true</optional>
 </dependency>

 <dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-boot-starter</artifactId>
     <version>3.3.2</version>
 </dependency>

 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
 </dependency>

配置檔案

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/book_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456
  resources:
    static-locations: classpath:static/
mybatis-plus:
  mapper-locations: classpath:mappers/*.xml
  type-aliases-package: com.blb.day12_spring_boot.entity

使用者實體類

@Data
@TableName("tb_user")
public class User implements Serializable {

    @TableId(type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private String realName;
}

書籍實體類

@Data
@TableName("tb_book")
public class Book {

    @TableId(type = IdType.AUTO)
    private Integer id;
    private String  bookName;
    private float price;
    private Integer typeId;
    private String author;
    private String publishOrg;
    private String publishTime;
    private Integer state;
    private String bookImage;
}

使用者Mapper介面

public interface UserMapper extends BaseMapper<User> {
}

書籍Mapper介面

public interface BookMapper extends BaseMapper<Book> {
}

使用者Service介面

public interface UserService extends IService<User> {
}

書籍Service介面

public interface BookService extends IService<Book>{
}

使用者Service介面實現類

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
}

書籍Service介面實現類

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

整合SpringMVC

匯入依賴

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

頁面跳轉的控制器

/**
 * 頁面跳轉控制器
 * 例: http://localhost:8080/pages/login 跳轉 login頁面
 */
@Controller
@RequestMapping("pages")
public class PageController {

    @RequestMapping("{page}")
    public String toPage(@PathVariable("page")String page){
        return page;
    }
}

使用者登入控制器

/**
 * 使用者登入控制器
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public String login(Model model, HttpSession session, String username, String password){
        //使用MyBatis-Plus的通用service查詢賬號和密碼
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username)
                .eq("password", password));
        //查詢失敗,提示錯誤
        if(user == null){
            model.addAttribute("msg","賬號或密碼錯誤");
            return "login";
        }
        //查詢成功,儲存user物件,跳轉書籍列表頁面
        session.setAttribute("user",user);
        return "redirect:/book/list";
    }
}

書籍控制器

/**
 * 書籍控制器
 */
@Controller
@RequestMapping("book")
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("list")
    public String list(Model model){
        //查詢所有書籍,跳轉到index.html
        List<Book> list = bookService.list();
        model.addAttribute("books",list);
        return "index";
    }
}

整合Thymeleaf

SpringBoot預設不支援JSP,支援的是比JSP更加優秀的模板引擎技術:Thymeleaf
Thymeleaf的優勢:

  • 動靜結合:Thymeleaf 在有網路和無網路的環境下皆可執行,即它可以讓美工在瀏覽器檢視頁面的靜態效果,也可以讓程式設計師在伺服器檢視帶資料的動態頁面效果。這是由於它支援 html 原型,然後在 html 標籤裡增加額外的屬性來達到模板+資料的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地執行;當有資料返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。

  • 開箱即用:它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表示式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴充套件和建立自定義的方言。

  • 多方言支援:Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美整合的可選模組,可以快速的實現表單繫結、屬性編輯器、國際化等功能。

  • 與SpringBoot完美整合,SpringBoot提供了Thymeleaf的預設配置,並且為Thymeleaf設定了檢視解析器,我們可以像以前操作jsp一樣來操作Thymeleaf。程式碼幾乎沒有任何區別,就是在模板語法上有區別。

匯入依賴

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

在resources/templates目錄中新建HTML檔案
頁面的html標籤中要新增名稱空間:xmlns:th=“http://www.thymeleaf.org”

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登入頁面</title>
</head>
<body>
    <h1>Hello 登入頁面</h1>
    <span th:text="${msg}" style="color:red"></span>
    <form action="/user/login" method="post">
        <input type="text" name="username" placeholder="請輸入賬號"><br>
        <input type="password" name="password" placeholder="請輸入密碼"><br>
        <input type="submit" value="登入">
    </form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
    <h1>首頁</h1>
    <table >
        <thead>
        <tr>
            <th>編號</th>
            <th>書名</th>
            <th>價格</th>
            <th>型別</th>
            <th>作者</th>
            <th>出版社</th>
            <th>出版日期</th>
            <th>狀態</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            <tr th:each="book : ${books}">
                <td th:text="${book.id}"></td>
                <td th:text="${book.bookName}"></td>
                <td th:text="${book.price}"></td>
                <td th:text="${book.typeId}"></td>
                <td th:text="${book.author}"></td>
                <td th:text="${book.publishOrg}"></td>
                <td th:text="${book.publishTime}"></td>
                <td th:text="${book.state}"></td>
                <td> </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

頁面中使用了Thymeleaf的兩種標籤:

  • th:text
    用於繫結文字內容,表示式${xx}類似於EL,繫結後臺傳遞的資料名稱
  • th:each
    用於迴圈遍歷集合內容,格式是: 變數名: ${集合名}

整合攔截器

登入功能需要新增SpringMVC的攔截器,否則使用者可以不通過驗證直接訪問書籍列表
思路是:

  1. 登入成功後儲存user物件到Session中
  2. 攔截器攔截使用者請求,如果Session中沒有user物件,就強制登入
  3. 如果有user物件就放行登入
public class MyLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //獲得session的user物件
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            //沒有登入,攔截,強制登入
            response.sendRedirect("/pages/login");
            return false;
        }
        //登入,就放行
        return true;
    }
}

配置攔截器

/**
 * 攔截器配置
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //新增攔截器
        registry.addInterceptor(new MyLoginInterceptor())
                //配置攔截路徑 所有
                .addPathPatterns("/**")
                //配置不攔截路徑
                .excludePathPatterns("/**/login","/**/*.css","/**/*.js");
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //重寫這個方法,對映靜態資原始檔
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }
}

結束


大家如果需要學習其他Java知識點,戳這裡 超詳細的Java知識點彙總