【java】SpringBoot中非連接數據庫的登錄模塊層和攔截器的使用

SpringBoot中非連接數據庫的登錄模塊層和攔截器的使用

邊看邊聽歌

開發簡單的登錄模塊,不涉及到數據庫的連接
攔截器是爲了防止用戶直接輸入主頁地址即可以不用登錄而進入主頁
理論上來說,這是不現實和不安全的

springboot中開發登錄模塊層
前端一個表單,前端使用的是thymeleaf模板
如下,其中的一些代碼基於上一篇博客而成:
在這裏插入圖片描述 需要具體注意的是1號處使用了th標籤設置了整個表單的提交路徑,即"/login" 2號處指定了表單以post請求的方式提交。
表單的主要代碼如下:

<form class="loginForm" th:action="@{/login}" method="post" action="../main/index.html">
				
                <div class="inputbox">
                    <label for="user" th:text="#{login.username}">Username</label>
                    <input id="user" type="text" name="username"  required/>
                </div>
                <div class="inputbox">
                    <label for="mima" th:text="#{login.password}">Password</label>
                    <input id="mima" type="password" name="password"  required/>
                </div>
				<div class="subBtn">
						<input type="checkbox"> [[#{login.remember}]]
                </div>
				<br/>
                <div class="subBtn">
                    <input type="submit" th:value="#{login.submit}" value="Sign" />
                    <input type="reset" th:value="#{login.reset}" value="Reset"/>
                </div>
				<br/>
				<div style="margin-left: 100px;">
                    <a href="#" th:href="@{/index.html(l='zh_CN')}">中文</a>
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href="" th:href="@{/index.html(l='en_US')}">English</a>
                </div>
            </form>

對應的,後端應該設置一個登錄專用的控制器,捕捉表單提交的請求和順帶的一些參數。
LoginController代碼如下,新建Controller包,包下面新建LoginController類
具體代碼如下:

package com.lagoon.springboot05.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.thymeleaf.util.StringUtils;

import java.util.Map;

@Controller
public class LoginController {

    @PostMapping("/login")
    public String login(String username, String password, Map<String,Object> map){
        //判斷用戶名不爲空
        if (!StringUtils.isEmpty(username)&&"123".equals(password)){

            //登錄成功
            return "redirect:/main.html";
        }

        //登錄失敗
        map.put("msg","用戶名或沒密碼錯誤!");
        return  "main/login";

    }
}

這裏做的登錄邏輯是簡單性的,判斷前端輸入的用戶名不爲空的話,且密碼等於123,則算登錄成功,否則算登錄失敗,反饋錯誤信息。
這裏需要注意的是,登錄成功是採用了重定向的防止轉發到主頁的,而main.html這個頁面實際上是不存在的,只是起說明登錄進的是主頁的作用,也是爲了讓防止表單數據重複提交的情況出現,讓用戶刷新頁面時不出現重複提交表單數據的提示框。
設置一個視圖控制器,讓/main.html這個響應路徑對應跳轉的頁面就是我們的主頁 index.html
如下:

package com.lagoon.springboot05.config;

import com.lagoon.springboot05.component.MyLocaleResolver;
import com.lagoon.springboot05.interceptor.LoginHandlerInterceptor;
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.WebMvcConfigurer;

@Configuration
public class MySpringMvcConfigurer {

    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
       return new WebMvcConfigurer(){
           //添加視圖控制器配置默認的歡迎頁
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("main/login");
                registry.addViewController("/index.html").setViewName("main/login");
                registry.addViewController("/main.html").setViewName("main/index");

            }

            //注入一個攔截器
           @Override
           public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor())
                        .addPathPatterns("/**")
                        .excludePathPatterns("/","/index.html","/login")
                        .excludePathPatterns("/css/*","/img/*","/js/*");

           }
       };
    }

    //區域解析器
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

主要是以下這個區域起作用
在這裏插入圖片描述
接着還有一個點就是前端展示登錄錯誤的信息
如下:
在這裏插入圖片描述使用了th:if標籤進行判斷,使用了th:text標籤進行實時顯示,實時顯示的前提是th:if裏的標籤裏的內容爲真值,用#調用string的判斷是否爲空的方法,所以意思也就是,如果存在錯誤信息,則展示錯誤信息的內容,即用戶名或密碼錯誤。如果沒有錯誤信息從後端傳過來,則啥也不展示,整個標籤體裏的內容不生效。

測試如下:
首先是登錄成功的情況
在這裏插入圖片描述在這裏插入圖片描述
成功登錄進系統,並且地址欄顯示的是main.html,這比顯示直接的響路徑有什麼好處
當你刷新時,是不用重複提交表單數據的。

接下來測試登錄失敗的情況:
在這裏插入圖片描述點擊登錄按鈕
在這裏插入圖片描述表單頭部顯示用戶登錄錯誤信息

登錄模塊至此,但是還會有一個小問題就是,用戶這個時候直接在地址欄裏輸入http://localhost:8080/main.html
其實也是可以進入到系統主頁的,這個實際上是不安全和不應該的
所以採用springboot的攔截器方式,來對登錄請求做一些攔截處理 。

在這裏插入圖片描述
新建一個攔截器包,包下新建一個登錄攔截器類
類中代碼具體如下:

package com.lagoon.springboot05.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

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

public class LoginHandlerInterceptor implements HandlerInterceptor {

    //調用目標方法之前被攔截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser!=null){
            return true;
        }
        request.setAttribute("msg","沒有權限,請先登錄!");
        request.getRequestDispatcher("/index.html").forward(request,response);
        return false;
    }
}

這個登錄攔截器類是繼承了HandlerInterceptor 這個接口的,並重寫了preHandle的方法,說明在登錄調用目標方法之前被攔截進行處理判斷。這裏就要在之前登錄控制器裏把登錄的用戶名存進session,所以之前的登錄控制器類代碼更改如下:

package com.lagoon.springboot05.controller;


        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.PostMapping;
        import org.thymeleaf.util.StringUtils;

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

@Controller
public class LoginController {

    @PostMapping("/login")
    public String login(HttpSession session,String username, String password, Map<String,Object> map){
        //判斷用戶名不爲空
        if (!StringUtils.isEmpty(username)&&"123".equals(password)){

            session.setAttribute("loginUser",username);
            //登錄成功
            return "redirect:/main.html";
        }

        //登錄失敗
        map.put("msg","用戶名或沒密碼錯誤!");
        return  "main/login";

    }
}

把當前登錄用戶名存進session,並命名爲loginUser。
接着在攔截器中進行判斷,取出session值,如果用戶名不爲空。則跳過攔截,如果用戶名爲空,則攔截登錄請求,並返回錯誤信息,用戶沒有權限進入主頁,因爲用戶沒有進行登錄

當然到了這裏只是把一個登錄攔截器定義好了,要使他生效,則需要將這個攔截器進行注入
在之前自定義的配置類裏進行重寫注入
代碼如下:

package com.lagoon.springboot05.config;

import com.lagoon.springboot05.component.MyLocaleResolver;
import com.lagoon.springboot05.interceptor.LoginHandlerInterceptor;
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.WebMvcConfigurer;

@Configuration
public class MySpringMvcConfigurer {

    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
       return new WebMvcConfigurer(){
           //添加視圖控制器配置默認的歡迎頁
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("main/login");
                registry.addViewController("/index.html").setViewName("main/login");
                registry.addViewController("/main.html").setViewName("main/index");

            }

            //注入一個攔截器
           @Override
           public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor())
                        .addPathPatterns("/**")
                        .excludePathPatterns("/","/index.html","/login")
                        .excludePathPatterns("/css/*","/img/*","/js/*");

           }
       };
    }

    //區域解析器
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

在這裏插入圖片描述

可以看出來攔截器調用addPathPatterns方法,默認攔截系統所有請求 "/**"代表所有請求
但是至此爲止,有些請求是不能被攔截的,比如登錄頁面的訪問請求,各種靜態資源的響應請求,如果被攔截了,則前端不會有樣式,所以.excludePathPatterns方法排除這些需要的請求

最後測試如下
直接訪問主頁的情況
在這裏插入圖片描述

回車

在這裏插入圖片描述

提示沒有權限,請先登錄!

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