SpringBoot Session接口驗證實現(xiàn)流程詳解
需求:只有用戶登錄成功后,才能訪問其它接口,否則提示需要進行登錄
項目倉庫地址:https://gitee.com/aiw-nine/springboot_session_verify
添加pom.xml
新建Spring Boot(2.7.2)項目,添加如下依賴:
<?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)建簡單的測試接口
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 {
/**
* 登錄,此處只做簡單測試
*
* @param user
* @param request
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public R<User> login(@RequestBody User user, HttpServletRequest request) {
// 此處應該和數(shù)據(jù)庫進行交互判斷,為做測試,簡單寫死
if (Objects.equals(user.getId(), 1) && Objects.equals(user.getName(), "Aiw")) {
// 登錄成功,將id存入session并返回登錄成功結果
request.getSession().setAttribute("user", user.getId());
request.getSession().setMaxInactiveInterval(1800); // 設置session失效時間為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("退出成功");
}
/**
* 此處做測試,看用戶在未登錄時,能否訪問到此接口
*
* @return
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public R<String> index() {
return R.success("首頁,訪問成功");
}
}使用過濾器實現(xiàn)
創(chuàng)建LoginCheckFilter.java類,實現(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;
/**
* 檢查用戶是否已經完成登錄(方式一:過濾器)
* 需要在啟動類上加上@ServletComponentScan注解,這樣才會掃描@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("攔截到的請求:{}", request.getRequestURI());
// 1、獲取本次請求的URI
String requestURI = request.getRequestURI();
// 定義不需要處理的請求路徑
String[] urls = new String[]{"/user/login", "/user/logout"};
// 2、判斷本次請求是否需要處理
boolean check = check(urls, requestURI);
// 3、如果不需要處理,則直接放行
if (check) {
log.info("本次請求{}不需要處理", 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、如果未登錄則返回未登錄結果,通過輸出流方式向客戶端頁面響應數(shù)據(jù)
log.info("用戶未登錄");
response.setContentType("application/json; charset=utf-8");
// 1、使用Fastjson(默認過濾null值)
response.getWriter().write(JSON.toJSONString(R.error("未登錄")));
// 2、使用默認的Jackson,此處關于Jackson配置的相關屬性會失效(即若在配置文件中配置過濾null值,這里返回時不會過濾)
// response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("未登錄")));
return;
}
/**
* 路徑匹配,檢查本次請求是否需要放行
*
* @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;
}
}修改啟動類
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);
}
}啟動項目,使用ApiPost進行接口測試。首先在未登錄狀態(tài)下,訪問/user/index接口

可以看到在未登錄時,訪問其它接口會失敗
此時先進行登錄,訪問/user/login接口

再次訪問/user/index接口

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

進行登錄,訪問/user/login接口

再次訪問/user/index接口

至此,全部完成,當然后期可以使用Spring Boot+JWT實現(xiàn)接口驗證
到此這篇關于SpringBoot Session接口驗證實現(xiàn)流程詳解的文章就介紹到這了,更多相關SpringBoot Session接口驗證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- springboot普通類中如何獲取session問題
- SpringBoot3整合MyBatis出現(xiàn)異常:Property?'sqlSessionFactory'or?'sqlSessionTemplate'?are?required
- SpringBoot集成redis與session實現(xiàn)分布式單點登錄
- SpringBoot整合SpringSession實現(xiàn)分布式登錄詳情
- SpringBoot?整合?Spring-Session?實現(xiàn)分布式會話項目實戰(zhàn)
- 詳解SpringBoot中@SessionAttributes的使用
- SpringBoot中HttpSessionListener的簡單使用方式
- SpringBoot2.x設置Session失效時間及失效跳轉方式
- SpringBoot下實現(xiàn)session保持方式
- Spring?Session(分布式Session共享)實現(xiàn)示例
相關文章
Spring Boot單元測試中使用mockito框架mock掉整個RedisTemplate的示例
今天小編就為大家分享一篇關于Spring Boot單元測試中使用mockito框架mock掉整個RedisTemplate的示例,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
Java子線程無法獲取Attributes的解決方法(最新推薦)
在Java多線程編程中,子線程無法直接獲取主線程設置的Attributes是一個常見問題,本文探討了這一問題的原因,并提供了兩種解決方案,對Java子線程無法獲取Attributes的解決方案感興趣的朋友一起看看吧2025-01-01
java計算給定字符串中出現(xiàn)次數(shù)最多的字母和該字母出現(xiàn)次數(shù)的方法
這篇文章主要介紹了java計算給定字符串中出現(xiàn)次數(shù)最多的字母和該字母出現(xiàn)次數(shù)的方法,涉及java字符串的遍歷、轉換及運算相關操作技巧,需要的朋友可以參考下2017-02-02
解決springboot項目啟動報錯Error creating bean with&nb
這篇文章主要介紹了解決springboot項目啟動報錯Error creating bean with name dataSourceScriptDatabaseInitializer問題,具有很好的參考價值,希望對大家有所幫助2024-03-03

