使用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;

    @Autowired
    public 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;

    @Autowired
    public UserServiceImpl(UserUtils userUtils) {
        this.userUtils = userUtils;
    }

    @Override
    public 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 {

    @Override
    public 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.mfbz.cn/a/296106.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

phpstudy上安装的composer和sockets扩展 步骤

1 安装composer 2 安装php sockets扩展 选择sockets扩展即可

三、Kubernetes(K8s)入门(一)

视频教程连接k8s 入门到微服务项目实战.xmind链接:https://pan.baidu.com/s/1q04euH7baE8eXNyG3kPPbA 提取码:jej4比较好的笔记 kubectl命令的语法如下: kubectl [command] [type] [name] [flags]comand:指定要对资源执行的操作…

几种常见的CSS三栏布局?介绍下粘性布局(sticky)?自适应布局?左边宽度固定,右边自适应?两种以上方式实现已知或者未知宽度的垂直水平居中?

几种常见的CSS三栏布局 流体布局 效果&#xff1a; 参考代码&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1…

Vue3 使用 Teleport 封装 一个 Dialog

文章目录 什么是Teleport ?用法:1. 通过 to 指定传送的位置2. 禁用 teleport3. 共享一个 Teleport封装一个Dialog效果:什么是Teleport ? 是一个内置组件,它可以将一个组件内部的一部分模板“传送”到该组件的 DOM 结构外层的位置去。 简单的说,Telep

网络协议

一、 网络协议 1.1 网络模型 1.1.1 OSI七层模型 开放系统互联参考模型&#xff08;Open System Interconnect&#xff09;是国际标准化组织&#xff08;ISO&#xff09;制订的一个用于计算机或通信系统间互联的标准体系。采用七层结构&#xff0c;自下而上依次为&#xff1a;…

pytest安装失败,报错Could not find a version that satisfies the requirement pytest

问题 安装pytest失败&#xff0c;尝试使用的命令有 pip install pytest pip3 install pytest pip install -U pytest pip install pytest -i https://pypi.tuna.tsinghua.edu.cn/simple但是都会报同样的错&#xff1a; 解决方案 发现可能是挂了梯子的原因&#xff0c;关掉…

听GPT 讲Rust源代码--compiler(15)

File: rust/compiler/rustc_arena/src/lib.rs 在Rust源代码中&#xff0c;rustc_arena/src/lib.rs文件定义了TypedArena&#xff0c;ArenaChunk&#xff0c;DroplessArena和Arena结构体&#xff0c;以及一些与内存分配和容器操作相关的函数。 cold_path<F: FnOnce,drop,new,…

Simply简洁博客主题源码 | EmlogPro主题模版

Simply是一款简约风格的Emlog博客模板&#xff0c;响应式布局、界面简单大方&#xff0c;实用性强&#xff01; 支持夜间模式&#xff0c;采用localStorage存储配置。IOS系统下支持随系统自动切换浅/深色模式。 文章页支持显示文章字数及阅读时间。 支持http/https 响应式主…

计算机进入BIOS - Win/Linux

计算机进入BIOS - Win/Linux 快捷键方法&#xff08;通用&#xff09;Win系统方法Linux系统方法 快捷键方法&#xff08;通用&#xff09; 此方法为通用方法&#xff0c;适用于任何型号的计算机&#xff0c;包括台式机和笔记本&#xff0c;也包括Win系统和Linux系统。 进入BI…

package-info.java delete

package-info.java delete

解决Gitee每次push都需要输入用户名和密码

其实很简单&#xff0c;只需要使用命令 git config --global credential.helper store 在你下次push时只需要再输入一次用户名和密码&#xff0c;电脑就会保存下来&#xff0c;之后就无需进行输入了。

宏基因组序列分析工具EukRep

文章&#xff1a;Genome-reconstruction for eukaryotes from complex natural microbial communities | bioRxiv 仓库&#xff1a;patrickwest/EukRep: Classification of Eukaryotic and Prokaryotic sequences from metagenomic datasets (github.com) 推荐使用conda进行安…

揭开 JavaScript 作用域的神秘面纱(上)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

Mac 安装Nginx教程

Nginx官网 Nginx官网英文 1.在终端输入brew search nginx 命令检查nginx是否安装了 2. 安装命令&#xff1a;brew install nginx 3. 查看Nginx信息命令brew info nginx 4. 启动 nginx方式&#xff1a;在终端里输入 nginx 5.查看 nginx 是否启动成功 在浏览器中访问http://l…

通过使用别名让 SQL 更简短-数据库教程shulanxt.com-帆软软件有限公司

MySQL视频教程导航 https://www.shulanxt.com/database/mysqlvideo/p1 SQL 别名 SQL 别名 通过使用 SQL&#xff0c;可以为表名称或列名称指定别名。 基本上&#xff0c;创建别名是为了让列名称的可读性更强。 列的 SQL 别名语法 SELECT column_name AS alias_name FROM …

【java】期末复习知识点

简单不先于复杂&#xff0c;而是在复杂之后。 文章目录 填空题封装包主类开发过程的改变interfaceabstract class访问控制关键字继承多态object 类Java I/O(输入/输出)异常线程和进程创建线程的两种基本方法 编程题Hello World编写Swing程序&#xff0c;显示一个空白窗口 填空题…

Huggy Lingo: 利用机器学习改进 Hugging Face Hub 上的语言元数据

太长不看版: Hub 上有不少数据集没有语言元数据&#xff0c;我们用机器学习来检测其语言&#xff0c;并使用 librarian-bots 自动向这些数据集提 PR 以添加其语言元数据。 Hugging Face Hub 已成为社区共享机器学习模型、数据集以及应用的存储库。随着 Hub 上的数据集越来越多&…

【AI视野·今日Sound 声学论文速览 第三十八期】Mon, 1 Jan 2024

AI视野今日CS.Sound 声学论文速览 Mon, 1 Jan 2024 Totally 5 papers &#x1f449;上期速览✈更多精彩请移步主页 Daily Sound Papers The Arrow of Time in Music -- Revisiting the Temporal Structure of Music with Distinguishability and Unique Orientability as the …

案例093:基于微信小程序的南宁周边乡村游设计与实现

文末获取源码 开发语言&#xff1a;Java 框架&#xff1a;SSM JDK版本&#xff1a;JDK1.8 数据库&#xff1a;mysql 5.7 开发软件&#xff1a;eclipse/myeclipse/idea Maven包&#xff1a;Maven3.5.4 小程序框架&#xff1a;uniapp 小程序开发软件&#xff1a;HBuilder X 小程序…

【CMake】1. VSCode 开发环境安装与运行

CMake 示例工程代码 https://github.com/LABELNET/cmake-simple 插件 使用 VSCode 开发C项目&#xff0c;安装 CMake 插件 CMakeCMake ToolsCMake Language Support &#xff08;建议&#xff0c;语法提示) 1. 配置 CMake Language Support , Windows 配置 donet 环境 这…