玩轉spring boot——簡單登陸認證

前言html


 

在一個web項目中,某些頁面是能夠匿名訪問的,但有些頁面則不能。spring mvc提供了HandlerInterceptor接口來應對,只須要重寫preHandle方法即可以實現此功能。那麼使用spring boot是怎麼實現的呢?java

 

1、準備工做git


 

pom.xml:github

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.carter659</groupId>
    <artifactId>spring13</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
    </parent>

    <name>spring13</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml

與以往的pom.xml沒有任何不一樣web

 

App.javaajax

package com.github.carter659.spring13;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 入口類 博客出處:http://www.cnblogs.com/GoodHelper/
 *
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
App.java

 

2、具體實現spring


 

1.新建控制器「MainController」文件:apache

package com.github.carter659.spring13;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * 控制器 博客出處:http://www.cnblogs.com/GoodHelper/
 *
 */
@Controller
public class MainController {

    @GetMapping("/")
    public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
        model.addAttribute("name", account);
        return "index";
    }

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

    @PostMapping("/loginPost")
    public @ResponseBody Map<String, Object> loginPost(String account, String password, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        if (!"123456".equals(password)) {
            map.put("success", false);
            map.put("message", "密碼錯誤");
            return map;
        }

        // 設置session
        session.setAttribute(WebSecurityConfig.SESSION_KEY, account);

        map.put("success", true);
        map.put("message", "登陸成功");
        return map;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 移除session
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        return "redirect:/login";
    }

}

 

講解MainController:微信

這裏的四個方法分別是:登陸後的頁面、登陸頁面、登陸ajax後臺方法和註銷。session

「loginPost」方法判斷當密碼爲「123456」時則設置session

「index」方法用來顯示session

「logout」方法用來移除session

 

 

2.新建「WebSecurityConfig」類文件:

package com.github.carter659.spring13;

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 登陸配置 博客出處:http://www.cnblogs.com/GoodHelper/
 *
 */
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {

    /**
     * 登陸session key
     */
    public final static String SESSION_KEY = "user";

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());

        // 排除配置
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/login**");

        // 攔截配置
        addInterceptor.addPathPatterns("/**");
    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            HttpSession session = request.getSession();
            if (session.getAttribute(SESSION_KEY) != null)
                return true;

            // 跳轉登陸
            String url = "/login";
            response.sendRedirect(url);
            return false;
        }
    }
}

 

「SecurityInterceptor」類繼承「HandlerInterceptorAdapter」,並從新「preHandle」方法,當session爲空時,則跳轉到登陸頁面

「WebSecurityConfig」類繼承「WebMvcConfigurerAdapter」,從新「addInterceptors」方法,其目的是設置攔截規則,excludePathPatterns爲須要排除的規則,addPathPatterns爲須要攔截的規則。

 

3、頁面


 

index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>玩轉spring boot——簡單登陸認證</title>
</head>
<body>
    <h1>玩轉spring boot——簡單登陸認證</h1>
    <h4>
        <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的博客</a>
    </h4>
    <h3 th:text="'登陸用戶:' + ${name}"></h3>
    
    <a href="/logout">註銷</a>
    <br />
    <a href="http://www.cnblogs.com/GoodHelper/">點擊訪問原版博客(www.cnblogs.com/GoodHelper)</a>
</body>
</html>

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>玩轉spring boot——簡單登陸認證</title>
</head>
<body>
    <h1>玩轉spring boot——簡單登陸認證</h1>
    <h4>
        <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的博客</a>
    </h4>
    <h3 th:text="'登陸用戶:' + ${name}"></h3>
    
    <a href="/logout">註銷</a>
    <br />
    <a href="http://www.cnblogs.com/GoodHelper/">點擊訪問原版博客(www.cnblogs.com/GoodHelper)</a>
</body>
</html>

 

4、運行效果


 

 

1.輸入錯誤的密碼後沒法登錄

2.輸入正確密碼後調整到首頁

3.在首頁顯示了登陸後的帳號

4.點擊註銷後返回登陸頁面

5.在未登陸的狀況下,直接輸入首頁網站「http://localhost:8080」後,沒法進入首頁,會強制跳轉到登陸頁面。

 


 

代碼:https://github.com/carter659/spring-boot-13.git

若是你以爲個人博客對你有幫助,能夠給我點兒打賞,左側微信,右側支付寶。

有可能就是你的一點打賞會讓個人博客寫的更好:)

 

返回玩轉spring boot系列目錄

相關文章
相關標籤/搜索