前言
在一个web项目中,某些页面是可以匿名访问的,但有些页面则不能。spring mvc提供了HandlerInterceptor接口来应对,只需要重写preHandle方法便可以实现此功能。那么使用spring boot是怎么实现的呢?
一、准备工作
pom.xml:
<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.0modelVersion> <groupId>com.github.carter659groupId> <artifactId>spring13artifactId> <version>0.0.1-SNAPSHOTversion> <packaging>jarpackaging> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>1.4.3.RELEASEversion> parent> <name>spring13name> <url>http://maven.apache.orgurl> <properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <java.version>1.8java.version> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-devtoolsartifactId> <optional>trueoptional> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
与以往的pom.xml没有任何不同
App.java
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); } }
二、具体实现
1.新建控制器“MainController”文件:
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 MaploginPost(String account, String password, HttpSession session) { Map 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后台方法和注销。
“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为需要拦截的规则。
三、页面
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>
四、运行效果
1.输入错误的密码后无法登陆
2.输入正确密码后调整到首页
3.在首页显示了登录后的账号
4.点击注销后返回登录页面
5.在未登录的情况下,直接输入首页网站“http://localhost:8080”后,无法进入首页,会强制跳转到登录页面。
代码:https://github.com/carter659/spring-boot-13.git
如果你觉得我的博客对你有帮助,可以给我点儿打赏,左侧微信,右侧支付宝。
有可能就是你的一点打赏会让我的博客写的更好:)
返回玩转spring boot系列目录