22. SpringBoot 實現登錄功能 (轉發 和 重定向) 和 攔截器功能 【前后端結合 主要學思想和使用】


 這里不連接數據庫 直接通過控制器判斷 和 SpringMVC 拓展實現: 

 

學習目標:

1 . 轉發 和 重定向,這里會詳細說明;

2. 攔截器的定義 和 注冊

3. thymeleaf 的一些綁定(略將 其實直接去取數據即可)

 

 

最后的項目結構:

 

 

1. 登錄功能的實現:

package com.bihu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class userController {
    
    /**
     *首頁登錄控制器
     * @return 然后視圖 直接訪問
     */
    @RequestMapping(value = {"/","/index"})
    public String login(){
        return "index";
    }

    /***
     * 登錄控制器
     * @param username  用戶名
     * @param password  密碼
     * @param message   登錄失敗分發的消息
     * @param session   Session對象 主要用來傳用戶名給攔截器
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> message, HttpSession session){
        //判斷登錄條件【這里不連接數據庫】
        if((username!=null && username.equals("Admin")) && (password != null && password.equals("123456")) ){
                session.setAttribute("loginUsername",username);     //設置用戶名 表示登錄成功 攔截器需要
                return "redirect:/main.html";  //防止重復提交!!!但是注意這里重定向不能是url,這個main.html不存在 因為我們的視圖在template目錄下 ,然而我們在拓展哪里增加了映射跳轉!!!
        }
        //登錄失敗那就到登錄頁面
        session.removeAttribute("loginUsername");   //防止BUG 移除用戶名
        message.put("msg","抱歉,請檢查您的賬號或密碼錯誤!");
        return "index";
    }






}
Usercontroller

里面都有注釋,但是為什么重定向是那樣的? 因為重定向是直接訪問url實現,但我們的視圖不是在靜態文件夾下的 我們的視圖是在 template模板文件夾下面,不能直接 xxxx.html 訪問的,

只能通過  返回視圖實現訪問  

所以我們需要返回main.html  這個是不存在的 但為什么會跳轉因為我們配置類中 拓展了 SpringMVC的功能:

 

 所以 SpringBoot的重定向功能你懂了沒???????

轉發是可以直接轉的,但是轉發也是不能在 template 文件夾下找視圖文件,所以你可以這樣:

 

 

所以這就是轉發和重定向,這就是 重定向訪問 不在靜態文件夾 下面的的視圖文件!!!!  但是直接用那就是另一種用法了 這里重點介紹前者。

 

2.攔截器功能

1.定義自己的攔截器:

package com.bihu.component;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    //自定義攔截器進行登錄權限 實現HandlerInterceptor類


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String username = (String) httpServletRequest.getSession().getAttribute("loginUsername");
        if ((username != null) && (!username.isEmpty())){   //判斷是否登錄
            return true;
        }

        httpServletRequest.setAttribute("msg","抱歉,請先登錄");
        //沒登錄 直接返回登錄頁面 這里看起來是轉發 其實這里是重定向(SpringMVC拓展寫了轉發)
        httpServletRequest.getRequestDispatcher("/index.html").forward(httpServletRequest,httpServletResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
LoginHandlerInterceptor

可以看到里面  主要是 判斷 用戶名 如果null  或 用戶名為空的話 那就轉發然后實現重新登錄的功能,而且還攜帶了信息給模板 ,模板也可以直接th:text("${msg}") 獲取的 ,可以看到 這里的 index.html 也是不存在的 ,也是通過SpringMVC 拓展功能實現 轉發 + 重定向 兩個功能。我認為就是這樣的 寫出來的也和自己想的一樣。

 

2.在配置類中注冊自己定義的攔截器  也是SpringMVC 拓展功能  里面的   addInterceptors ,  詳細看代碼:

package com.bihu.config;

import com.bihu.component.LoginHandlerInterceptor;
import com.bihu.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class mConfig extends WebMvcConfigurerAdapter {

    //添加請求映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index.html").setViewName("/index");    //登錄頁面的 充當重定向功能
        registry.addViewController("/main.html").setViewName("/dashboard");     //登錄成功的 充當重定向功能
    }

    //注冊攔截器(自己寫的)
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //靜態資源就不用配置了 靜態資源SpringBoot 已自動配置好了
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**")         //攔截全部
                .excludePathPatterns("/index.html","/","/login"); //排除登錄功能請求
    }

    
    
    //添加自定義區域代碼解析器【國際化】
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

}
mConfig

 

總結:為什么要寫攔截器?  正是因為 如果配,我們那些 比如 登錄成功的頁面 不就直接可以訪問了嗎  那登錄毫無沒意義。

比如:

http://localhost:8080/main.html

main.index 是不存在的 ,正式因為重定向 我們才可以再次跳轉到 dashboard這個視圖。

 

 

 

⭐ 靜態資源在SpringBoot 中 是不用配置的。 靜態資源SpringBoot 已自動配置好了

 

 

 

下面是模板代碼 登錄頁視圖  注意看下那些thymeleaf表達式吧:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Signin Template for Bootstrap</title>
    <!-- Bootstrap core CSS -->
    <link href="asserts/css/bootstrap.min.css" rel="stylesheet" th:href="@{/webjars/bootstrap/4.0.0/dist/css/bootstrap.css}" />
    <!-- Custom styles for this template -->
    <link href="asserts/css/signin.css" rel="stylesheet" th:href="@{/asserts/css/signin.css}" />
</head>

<body class="text-center">
<form class="form-signin"  th:action="@{/login}" method="post">
    <img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.title}">Please sign in</h1>
        <p style="color: red" th:text="${msg}" ></p>
    <label class="sr-only" >Username</label>
    <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" placeholder="Username" required="" autofocus="">
    <label class="sr-only" th:text="#{login.passwprd}" >Password</label>
    <input type="password" name="password" class="form-control" th:placeholder="#{login.passwprd}" placeholder="Password" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.Remember}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.sign}" >Sign in</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
    <a class="btn btn-sm" th:href="@{/?l=zh_CN}">中文</a>
    <a class="btn btn-sm" th:href="@{/?l=en_US}">English</a>
</form>

</body>

</html>
index.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM