SpringBoot學習(4):攔截器以及相關的SpringMVC的擴展

1.在SpringBoot使用 thymeleaf 模板引擎

小提示:靜態資源文件都放在 resources 文件夾目錄下,其中 templates 放置的是 html 文件,而 static 放置的是 js、css、img 等靜態資源文件。目錄結構如下:

  1.1在pom.xml引入,會自動導入依賴

<dependency>
     <groupId>org.thymeleaf</groupId>
     <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

  1.2關於模板引擎 thymeleaf 用法

    1.2.1 在標籤 html 上面加上  xmlns:th="http://www.thymeleaf.org" 纔可以使用,th的語法

<html lang="en" xmlns:th="http://www.thymeleaf.org">
</html>

    1.2.2 具體語法的使用

      要鏈接相關的本地靜態資源的時候:其中 static 表示靜態資源可以直接省略不寫

<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">

      如果消息爲空則不顯示:

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

      變量的顯示

<a>[[${session.loginUser}]]</a>

2. SpringBoot擴展SpringMVC

  2.1 在與運行文件 DemoApplication 文件同級的文件下面建立一個叫 config 的包,然後在 config 包裏面建立一個 MyMvcConfig 的類:目錄如下

  2.2 裏面具體的代碼如下:使用工具 IDEA 的快捷鍵 ctrl+s 可以快速重寫相關的類。

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

// 擴展 MVC
// 增加視圖層
@Configuration // 這個註解用於定義配置類
public class MyMvcConfig implements WebMvcConfigurer {
    // 試圖 映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }
    // 註冊bean 重寫裏面的攔截器方法 說明要攔截的東西
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**") // 把所有的都攔截掉
                .excludePathPatterns("/index.html",
 "/", "/login","/css/**", "/js/**", "/img/**"); // 排除括號裏面的
    }
}

  2.3 對登入進行攔截,防止在地址欄亂輸入也能進入系統

相關代碼如下:

// 重新上線 HandlerInterceptor 這個類
public class LoginHandlerInterceptor implements HandlerInterceptor {
   // 重寫這三個方法 HttpServletRequest HttpServletResponse 爲 servlet 內置的
    @Override
    public boolean preHandle(HttpServletRequest request,
     HttpServletResponse response, Object handler) throws Exception {
        // 1. 拿到用戶請求的信息,return true 表示放行 retun false 表示攔截
        // 2. 登入成功之後,應該有用戶的 session (token) 就是用戶的標誌
        Object loginUser = request.getSession().getAttribute("loginUser");
        if(loginUser == null){
            request.setAttribute("msg","請先登入");
            // 將請求進行轉發操作
            request.getRequestDispatcher("/index.html").forward(request,resopnse);
            return false;
        }else{
            // 否則進行放行
            return true;
        }
    } 
}

3. 關於登入

 controller層的代碼如下:

// 被@Controller標記的類實際上就是個SpringMVC Controller對象,它是一個控制器類
public class LoginController {
    @RequestMapper("/login")
    public String login(@RequestParam("username"), @RequestParam("password"),
    Model model, HttpSession session){
        // 具體的業務代碼 其中 StringUtils 使用 th 模板引擎的工具類
        if(StringUtils.isEmpty(username) && "123".equals(password)){
            // 登入時隨便把 loginUser 這個登入的標誌也存入到 session裏面
            session.setAttribute("loginUser", username);
            // 重定向到配置好的首頁
            return "redirect:/main.html";
        }else{
            // 如果 用戶名爲空 密碼不是 123 的話就提示,並且停留在首頁
            model.addAttribite("msg", "用戶名或者密碼錯誤");
            return "index";
        }
    }
}

 前臺的代碼如下:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <body>
        <!-- 下面是一個表單的 要注意的是:一定要寫 name="username" -->
        <form th:action="@{/login}">
            <input type="text" name="username" />
            <input type="password" name="password" />
            <button type="submit"></button>
        </form>
    </body>
</html>

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章