SpringBoot Session接口驗(yàn)證實(shí)現(xiàn)流程詳解
需求:只有用戶登錄成功后,才能訪問(wèn)其它接口,否則提示需要進(jìn)行登錄
項(xiàng)目倉(cāng)庫(kù)地址:https://gitee.com/aiw-nine/springboot_session_verify
添加pom.xml
新建Spring Boot(2.7.2)項(xiàng)目,添加如下依賴:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.aiw</groupId>
<artifactId>waimai</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>waimai</name>
<description>waimai</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>創(chuàng)建簡(jiǎn)單的測(cè)試接口
package com.aiw.springboot_session_verify.controller;
import com.aiw.springboot_session_verify.entity.User;
import com.aiw.springboot_session_verify.response.R;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 登錄,此處只做簡(jiǎn)單測(cè)試
*
* @param user
* @param request
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public R<User> login(@RequestBody User user, HttpServletRequest request) {
// 此處應(yīng)該和數(shù)據(jù)庫(kù)進(jìn)行交互判斷,為做測(cè)試,簡(jiǎn)單寫(xiě)死
if (Objects.equals(user.getId(), 1) && Objects.equals(user.getName(), "Aiw")) {
// 登錄成功,將id存入session并返回登錄成功結(jié)果
request.getSession().setAttribute("user", user.getId());
request.getSession().setMaxInactiveInterval(1800); // 設(shè)置session失效時(shí)間為30分鐘
return R.success("登錄成功", user);
}
return R.fail("登錄失敗");
}
/**
* 退出登錄
*
* @param request
* @return
*/
@RequestMapping(value = "/logout", method = RequestMethod.POST)
public R<String> logout(HttpServletRequest request) {
request.getSession().removeAttribute("user");
return R.success("退出成功");
}
/**
* 此處做測(cè)試,看用戶在未登錄時(shí),能否訪問(wèn)到此接口
*
* @return
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public R<String> index() {
return R.success("首頁(yè),訪問(wèn)成功");
}
}使用過(guò)濾器實(shí)現(xiàn)
創(chuàng)建LoginCheckFilter.java類,實(shí)現(xiàn)Filter接口
package com.aiw.springboot_session_verify.filter;
import com.aiw.springboot_session_verify.response.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
/**
* 檢查用戶是否已經(jīng)完成登錄(方式一:過(guò)濾器)
* 需要在啟動(dòng)類上加上@ServletComponentScan注解,這樣才會(huì)掃描@WebFilter注解
*/
@Slf4j
@WebFilter
public class LoginCheckFilter implements Filter {
// 路徑匹配器,支持通配符
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
log.info("攔截到的請(qǐng)求:{}", request.getRequestURI());
// 1、獲取本次請(qǐng)求的URI
String requestURI = request.getRequestURI();
// 定義不需要處理的請(qǐng)求路徑
String[] urls = new String[]{"/user/login", "/user/logout"};
// 2、判斷本次請(qǐng)求是否需要處理
boolean check = check(urls, requestURI);
// 3、如果不需要處理,則直接放行
if (check) {
log.info("本次請(qǐng)求{}不需要處理", requestURI);
filterChain.doFilter(request, response);
return;
}
// 4、判斷登錄狀態(tài),如果已登錄,則直接放行
if (Objects.nonNull(request.getSession().getAttribute("user"))) {
log.info("用戶已登錄,用戶id為:{}", request.getSession().getAttribute("user"));
filterChain.doFilter(request, response);
return;
}
// 5、如果未登錄則返回未登錄結(jié)果,通過(guò)輸出流方式向客戶端頁(yè)面響應(yīng)數(shù)據(jù)
log.info("用戶未登錄");
response.setContentType("application/json; charset=utf-8");
// 1、使用Fastjson(默認(rèn)過(guò)濾null值)
response.getWriter().write(JSON.toJSONString(R.error("未登錄")));
// 2、使用默認(rèn)的Jackson,此處關(guān)于Jackson配置的相關(guān)屬性會(huì)失效(即若在配置文件中配置過(guò)濾null值,這里返回時(shí)不會(huì)過(guò)濾)
// response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("未登錄")));
return;
}
/**
* 路徑匹配,檢查本次請(qǐng)求是否需要放行
*
* @param urls
* @param requestURI
* @return
*/
public boolean check(String[] urls, String requestURI) {
for (String url : urls) {
boolean match = PATH_MATCHER.match(url, requestURI);
if (match) return true;
}
return false;
}
}修改啟動(dòng)類
package com.aiw.springboot_session_verify;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class SpringbootSessionVerifyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSessionVerifyApplication.class, args);
}
}啟動(dòng)項(xiàng)目,使用ApiPost進(jìn)行接口測(cè)試。首先在未登錄狀態(tài)下,訪問(wèn)/user/index接口

可以看到在未登錄時(shí),訪問(wèn)其它接口會(huì)失敗
此時(shí)先進(jìn)行登錄,訪問(wèn)/user/login接口

再次訪問(wèn)/user/index接口

即登錄成功后,可以成功訪問(wèn)該接口;為保證后續(xù)操作,此處再訪問(wèn)/user/logout接口,刪除后端的session
使用攔截器實(shí)現(xiàn)
創(chuàng)建LoginCheckInterceptor.java類,實(shí)現(xiàn)HandlerInterceptor接口
package com.aiw.springboot_session_verify.interceptor;
import com.aiw.springboot_session_verify.response.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;
/**
* 檢查用戶是否已經(jīng)完成登錄(方式二:攔截器)
* 需要在實(shí)現(xiàn)WebMvcConfigurer接口的配置類中重寫(xiě)addInterceptors方法,將攔截器注冊(cè)到容器,并指定攔截規(guī)則
*/
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//1.獲取請(qǐng)求
log.info("攔截的請(qǐng)求:{}", request.getRequestURI());
//2.判斷用戶是否登錄
HttpSession session = request.getSession();
// 若存在,則放行
if (Objects.nonNull(session.getAttribute("user"))) return true;
//攔截住,并給前端頁(yè)面返回未登錄信息,以輸出流的方式,json格式返回
response.setContentType("application/json; charset=utf-8");
// 1、使用Fastjson(默認(rèn)過(guò)濾null值)
response.getWriter().write(JSON.toJSONString(R.error("未登錄")));
// 2、使用默認(rèn)的Jackson,在配置文件中關(guān)于Jackson配置的相關(guān)屬性會(huì)失效
//response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("未登錄")));
return false;
}
}注冊(cè)攔截器,新建配置類WebConfig.java,實(shí)現(xiàn)WebMvcConfigurer接口
package com.aiw.springboot_session_verify.config;
import com.aiw.springboot_session_verify.interceptor.LoginCheckInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 注冊(cè)攔截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginCheckInterceptor())
.addPathPatterns("/**")
// 排除的請(qǐng)求路徑
.excludePathPatterns("/user/login", "/user/logout");
}
}注釋掉LoginCheckFilter.java類,再注釋掉啟動(dòng)類上的@ServletComponentScan注解,防止過(guò)濾器的干擾,啟動(dòng)項(xiàng)目。首先在未登錄狀態(tài)下,訪問(wèn)/user/index接口

進(jìn)行登錄,訪問(wèn)/user/login接口

再次訪問(wèn)/user/index接口

至此,全部完成,當(dāng)然后期可以使用Spring Boot+JWT實(shí)現(xiàn)接口驗(yàn)證
到此這篇關(guān)于SpringBoot Session接口驗(yàn)證實(shí)現(xiàn)流程詳解的文章就介紹到這了,更多相關(guān)SpringBoot Session接口驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot普通類中如何獲取session問(wèn)題
- SpringBoot3整合MyBatis出現(xiàn)異常:Property?'sqlSessionFactory'or?'sqlSessionTemplate'?are?required
- SpringBoot集成redis與session實(shí)現(xiàn)分布式單點(diǎn)登錄
- SpringBoot整合SpringSession實(shí)現(xiàn)分布式登錄詳情
- SpringBoot?整合?Spring-Session?實(shí)現(xiàn)分布式會(huì)話項(xiàng)目實(shí)戰(zhàn)
- 詳解SpringBoot中@SessionAttributes的使用
- SpringBoot中HttpSessionListener的簡(jiǎn)單使用方式
- SpringBoot2.x設(shè)置Session失效時(shí)間及失效跳轉(zhuǎn)方式
- SpringBoot下實(shí)現(xiàn)session保持方式
- Spring?Session(分布式Session共享)實(shí)現(xiàn)示例
相關(guān)文章
Spring Boot單元測(cè)試中使用mockito框架mock掉整個(gè)RedisTemplate的示例
今天小編就為大家分享一篇關(guān)于Spring Boot單元測(cè)試中使用mockito框架mock掉整個(gè)RedisTemplate的示例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
Java子線程無(wú)法獲取Attributes的解決方法(最新推薦)
在Java多線程編程中,子線程無(wú)法直接獲取主線程設(shè)置的Attributes是一個(gè)常見(jiàn)問(wèn)題,本文探討了這一問(wèn)題的原因,并提供了兩種解決方案,對(duì)Java子線程無(wú)法獲取Attributes的解決方案感興趣的朋友一起看看吧2025-01-01
java計(jì)算給定字符串中出現(xiàn)次數(shù)最多的字母和該字母出現(xiàn)次數(shù)的方法
這篇文章主要介紹了java計(jì)算給定字符串中出現(xiàn)次數(shù)最多的字母和該字母出現(xiàn)次數(shù)的方法,涉及java字符串的遍歷、轉(zhuǎn)換及運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-02-02
idea中寫(xiě)sql語(yǔ)句沒(méi)有提示字段的問(wèn)題
在IDEA中編寫(xiě)SQL時(shí)如果沒(méi)有字段提示,通常是因?yàn)闆](méi)有設(shè)置注入語(yǔ)言,解決方法是通過(guò)快捷鍵Alt+Enter選擇“注入語(yǔ)言或引用”,然后選擇相應(yīng)的數(shù)據(jù)庫(kù)(如MySQL),之后重新輸入SQL語(yǔ)句即可,此方法可以有效解決IDEA中SQL語(yǔ)句提示問(wèn)題,提高開(kāi)發(fā)效率2024-09-09
java實(shí)現(xiàn)學(xué)生宿舍系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)學(xué)生宿舍系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
解決springboot項(xiàng)目啟動(dòng)報(bào)錯(cuò)Error creating bean with&nb
這篇文章主要介紹了解決springboot項(xiàng)目啟動(dòng)報(bào)錯(cuò)Error creating bean with name dataSourceScriptDatabaseInitializer問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助2024-03-03
使用webmagic實(shí)現(xiàn)爬蟲(chóng)程序示例分享
這篇文章主要介紹了使用webmagic實(shí)現(xiàn)爬蟲(chóng)程序示例,需要的朋友可以參考下2014-04-04

