SpringBoot Session接口驗證實現(xiàn)流程詳解
需求:只有用戶登錄成功后,才能訪問其它接口,否則提示需要進(jì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) { // 此處應(yīng)該和數(shù)據(jù)庫進(jìn)行交互判斷,為做測試,簡單寫死 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失效時間為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; /** * 檢查用戶是否已經(jīng)完成登錄(方式一:過濾器) * 需要在啟動類上加上@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、如果未登錄則返回未登錄結(jié)果,通過輸出流方式向客戶端頁面響應(yīng)數(shù)據(jù) log.info("用戶未登錄"); response.setContentType("application/json; charset=utf-8"); // 1、使用Fastjson(默認(rèn)過濾null值) response.getWriter().write(JSON.toJSONString(R.error("未登錄"))); // 2、使用默認(rèn)的Jackson,此處關(guān)于Jackson配置的相關(guān)屬性會失效(即若在配置文件中配置過濾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進(jìn)行接口測試。首先在未登錄狀態(tài)下,訪問/user/index
接口
可以看到在未登錄時,訪問其它接口會失敗
此時先進(jìn)行登錄,訪問/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; /** * 檢查用戶是否已經(jīng)完成登錄(方式二:攔截器) * 需要在實現(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(默認(rèn)過濾null值) response.getWriter().write(JSON.toJSONString(R.error("未登錄"))); // 2、使用默認(rèn)的Jackson,在配置文件中關(guān)于Jackson配置的相關(guān)屬性會失效 //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
接口
進(jìn)行登錄,訪問/user/login
接口
再次訪問/user/index
接口
至此,全部完成,當(dāng)然后期可以使用Spring Boot+JWT實現(xiàn)接口驗證
到此這篇關(guān)于SpringBoot Session接口驗證實現(xiàn)流程詳解的文章就介紹到這了,更多相關(guān)SpringBoot Session接口驗證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 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設(shè)置Session失效時間及失效跳轉(zhuǎn)方式
- SpringBoot下實現(xiàn)session保持方式
- Spring?Session(分布式Session共享)實現(xiàn)示例
相關(guān)文章
Java利用apache ftp工具實現(xiàn)文件上傳下載和刪除功能
這篇文章主要為大家詳細(xì)介紹了Java利用apache ftp工具實現(xiàn)文件上傳下載、刪除功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06Mybatis基礎(chǔ)概念與高級應(yīng)用小結(jié)
這篇文章主要介紹了Mybatis基礎(chǔ)回顧與高級應(yīng)用,本文內(nèi)容有點小長,希望大家耐心閱讀,此文結(jié)合實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06SpringDataElasticsearch與SpEL表達(dá)式實現(xiàn)ES動態(tài)索引
這篇文章主要介紹了SpringDataElasticsearch與SpEL表達(dá)式實現(xiàn)ES動態(tài)索引,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-09-09SpringBoot?@Value與@ConfigurationProperties二者有哪些區(qū)別
這篇文章主要介紹了SpringBoot?@Value與@ConfigurationProperties二者的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10Java實現(xiàn)Fibonacci(斐波那契)取余的示例代碼
這篇文章主要介紹了Java實現(xiàn)Fibonacci取余的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03Mybatisplus實現(xiàn)JSON處理器的示例代碼
Mybatisplusjson是基于Mybatisplus開發(fā)的一個json工具庫,本文主要介紹了Mybatisplus實現(xiàn)JSON處理器的示例代碼,具有一定的參考價值,感興趣的可以了解一下2024-03-03SpringBoot中@EnableAutoConfiguration和@Configuration的區(qū)別
這篇文章主要介紹了SpringBoot中@EnableAutoConfiguration和@Configuration的區(qū)別,@SpringBootApplication相當(dāng)于@EnableAutoConfiguration,@ComponentScan,@Configuration三者的集合,需要的朋友可以參考下2023-08-08Spring Boot中進(jìn)行 文件上傳和 文件下載功能實現(xiàn)
開發(fā)Wb應(yīng)用時,文件上傳是很常見的一個需求,瀏覽器 通過 表單形式 將 文件 以 流的形式傳遞 給 服務(wù)器,服務(wù)器再對上傳的數(shù)據(jù)解析處理,下面將通過一個案例講解使用 SpringBoot 實現(xiàn) 文件上傳,感興趣的朋友一起看看吧2024-07-07