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

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

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

一、登录功能实现

controller

java 复制代码
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

java 复制代码
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

java 复制代码
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

java 复制代码
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的组件扫描~

java 复制代码
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仓库,可按需获取~

使用过滤器实现一个最简单的登录认证功能https://gitee.com/he-yunlin/filter-login.git

相关推荐
万亿少女的梦16815 分钟前
基于Spring Boot、Java与MySQL的网络订餐系统设计与实现
java·spring boot·mysql·系统设计·网络订餐
咩咩啃树皮9 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
鱟鲥鳚9 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
大模型码小白11 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司11 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地12 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun31415912 小时前
TCP超时重传机制是为了解决什么问题?
java
莫逸风15 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
z1234567898615 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
yaoxin52112316 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python