使用HttpSession和过滤器实现一个简单的用户登录认证的功能

这篇文章分享一下怎么通过session结合过滤器来实现控制登录访问的功能,涉及的代码非常简单,通过session保存用户登录的信息,如果没有用户登录的话,会在过滤器中处理,重定向回登录页面。

创建一个springboot项目,添加springbooot-starter-web和lombok的依赖。创建对应的实体类、controller、service,并创建两个简单的html页面测试过滤器的效果。

一、登录功能实现

controller

package cn.edu.sgu.www.login.controller;import cn.edu.sgu.www.login.entity.User;
import cn.edu.sgu.www.login.service.UserService;
import cn.edu.sgu.www.login.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;/*** @author heyunlin* @version 1.0*/
@RestController
@RequestMapping(path = "/user", produces = "application/json;charset=utf-8")
public class UserController {private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@RequestMapping(value = "/login", method = RequestMethod.POST)public void login(User user) throws IOException {userService.login(user);UserUtils.getResponse().sendRedirect("/index.html");}}

service

UserService

package cn.edu.sgu.www.login.service;import cn.edu.sgu.www.login.entity.User;/*** @author heyunlin* @version 1.0*/
public interface UserService {/*** 登录认证* @param user 用户输入的信息*/void login(User user);
}

UserServiceImpl

package cn.edu.sgu.www.login.service.impl;import cn.edu.sgu.www.login.entity.User;
import cn.edu.sgu.www.login.service.UserService;
import cn.edu.sgu.www.login.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author heyunlin* @version 1.0*/
@Service
public class UserServiceImpl implements UserService {private final UserUtils userUtils;@Autowiredpublic UserServiceImpl(UserUtils userUtils) {this.userUtils = userUtils;}@Overridepublic void login(User user) {String username = user.getUsername();String password = user.getPassword();if (username == null || "".equals(username)) {throw new RuntimeException("用户名不能为空~");} else if (password == null || "".equals(password)) {throw new RuntimeException("密码不能为空~");} else {if (username.equals("admin") && password.equals("12345")) {userUtils.getSession().setAttribute("user", user);} else {throw new RuntimeException("用户名或密码错误!");}}}}

二、过滤器实现资源访问控制

LoginFilter

package cn.edu.sgu.www.login.filter;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;/*** 登录过滤器* @author heyunlin* @version 1.0*/
@WebFilter(filterName = "loginFilter", urlPatterns = {"/", "/html/*", "/index.html"})
public class LoginFilter implements Filter {@Overridepublic void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpSession session = request.getSession();// 获取登录信息Object obj = session.getAttribute("user");if (obj == null) { // 未登录,重定向到登录页/** 登录页面的地址*/String loginPage = "/login.html";// 获取响应对象HttpServletResponse response = (HttpServletResponse) resp;response.sendRedirect(loginPage);} else { // 当前有用户登录,放行filterChain.doFilter(req, resp);}}}

在任意配置类上使用@ServletComponentScan("cn.edu.sgu.www.login.filter")开启servlet的组件扫描~

package cn.edu.sgu.www.login;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;@ServletComponentScan("cn.edu.sgu.www.login.filter")
@SpringBootApplication
public class FilterLoginApplication {public static void main(String[] args) {SpringApplication.run(FilterLoginApplication.class, args);}}

文章设计的代码已上传到git仓库,可按需获取~

使用过滤器实现一个最简单的登录认证功能icon-default.png?t=N7T8https://gitee.com/he-yunlin/filter-login.git

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/325253.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Turtle库】海绵宝宝

在这个充满创意与想象力的时代,我们决定挑战一项富有意义且有趣的使命——使用Python编程语言绘制海绵宝宝。这个经典的角色,以其独特的魅力和无与伦比的搞笑天赋,已经成为了无数人心中的童年回忆。现在,我们希望通过Python的强大…

了解统计分析中的岭回归

一、介绍 在统计建模和机器学习领域,回归分析是用于理解变量之间关系的基本工具。在各种类型的回归技术中,岭回归是一种特别有用的方法,尤其是在处理多重共线性和过拟合时。本文深入探讨了岭回归的概念、其数学基础、应用、优点和局限性。 在…

【unity】Obi插件架构组成(参数详细解释)——解算器四面板设置、三种更新器、参与者介绍

文章目录 一、架构(Architecture)1.1 Obi解算器(ObiSolver)1.2 ObiUpdater1.3 ObiActorBlueprint1.4 Obi参与者(ObiActor,如ObiRope等) 二、Obi解算器(ObiSolver)2.1 解算…

机器视觉兄弟们,没有项目订单,机器视觉项目行业难题来了

产品没一个正形,光源像是打了几十年的光棍一样,偏偏配不上,n次“相亲”之后图像硬是“阴晴圆缺”,老板阴阳怪气你这打不出来,给客户看之后说,这都打不出来,你们不行啊。 我听了后真想&#xff…

基于单片机的农田灌溉系统(论文+源码)

1.系统设计 本系统主要实现如下目标: 1.可以实时监测土壤湿度; 2.土壤湿度太低时,进行浇水操作; 3.可以按键设置湿度的触发阈值; 4. 可以实现远程操控 5.可以实现手…

跟随chatgpt从零开始安装git(Windows系统)

为什么我们要安装Git?Git有什么用? 1. 版本控制:Git 可以追踪代码的所有变化,记录每个提交的差异,使您能够轻松地回溯到任何历史版本或比较不同版本之间的差异。 2. 分支管理:通过 Git 的分支功能&#xff…

​已解决java.lang.ArrayIndexOutOfBoundsException异常的正确解决方法,亲测有效!!!​

已解决java.lang.ArrayIndexOutOfBoundsException异常的正确解决方法,亲测有效!!! 目录 报错问题 解决思路 解决方法 总结 Q1 - 报错问题 java.long.ArrayIndexOutOfBoundsException 是Java中的一个运行时异常​&#xff0c…

PHPStudy快速搭建网站并结合内网穿透远程访问本地站点

文章目录 [toc]使用工具1. 本地搭建web网站1.1 下载phpstudy后解压并安装1.2 打开默认站点,测试1.3 下载静态演示站点1.4 打开站点根目录1.5 复制演示站点到站网根目录1.6 在浏览器中,查看演示效果。 2. 将本地web网站发布到公网2.1 安装cpolar内网穿透2…

04set注入专题/简单类型/数组/List/Set/Map/空字符串/null/特殊符号

1.1注入外部Bean 在之前使用的案例就是注入外部Bean的方式。 <!-- class属性声明要管理哪个类中的对象 property标签的name是提示set方法名ref标签指明注入的bean的id--><bean id"userServiceBean" class"com.powernode.spring6.service.UserService…

磁盘损坏0x80070570

要修复的文件在E盘&#xff0c;那就输入&#xff1a;chkdsk e&#xff1a; /f 原文&#xff1a;https://www.haozhuangji.com/xtjc/111213592.html

WEB前端知识点整理(HTML+CSS+JAVASCRTPT)

1.HTML5、HTML和XHTML都是用于创建网页的标记语言&#xff0c;它们之间有一些关键的区别&#xff1a; &#xff08;1&#xff09;语法和规范&#xff1a; HTML5&#xff1a; HTML5是HTML标准的最新版本&#xff0c;引入了许多新的元素和API&#xff0c;以提供更丰富的功能和更…

Keras实现seq2seq

概述 Seq2Seq是一种深度学习模型&#xff0c;主要用于处理序列到序列的转换问题&#xff0c;如机器翻译、对话生成等。该模型主要由两个循环神经网络&#xff08;RNN&#xff09;组成&#xff0c;一个是编码器&#xff08;Encoder&#xff09;&#xff0c;另一个是解码器…