You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot未登录用户直接访问内容URL时如何跳转至登录注册页

现有代码的问题

  • 校验逻辑仅覆盖了/ideas路径,其他需要鉴权的路径(比如你提到的/someContent)没有对应的校验规则,用户访问这些路径时自然不会触发跳转
  • 逻辑顺序错误:你在uID还没做非空判断的情况下,就直接把uID作为参数传入userService.findById(),如果uID为null,这一步会直接抛出空指针异常,后续的跳转逻辑根本不会执行
  • 没有全局统一的校验规则,每个控制器都手写校验逻辑维护成本极高,很容易出现漏加的情况

修复方案

1 先修复当前控制器代码的逻辑错误

把非空判断移到数据库查询之前,避免空指针异常:

@RequestMapping("/ideas")
public String home(HttpSession session, Model model) {
    Long uID = (Long) session.getAttribute("userId");
    // 先判断uID是否为空,再查询用户
    if (uID == null) {
        return "redirect:/";
    }
    User user = userService.findById(uID);
    if (user == null) {
        return "redirect:/";
    }
    Iterable<Idea> ideas = ideaService.allIdeasH();
    model.addAttribute("ideas", ideas);
    model.addAttribute("user", user);
    return "index.jsp";
}

2 配置全局登录拦截器(推荐)

不需要每个控制器都重复写校验逻辑,统一拦截所有需要鉴权的路径:

第一步:自定义拦截器类

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            // 未登录,跳转到登录页
            response.sendRedirect("/");
            return false;
        }
        // 已登录放行
        return true;
    }
}

第二步:注册拦截器,配置拦截规则

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 {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                // 拦截所有需要登录才能访问的路径,/** 代表所有路径
                .addPathPatterns("/**")
                // 排除登录注册页、静态资源等不需要鉴权的路径
                .excludePathPatterns("/", "/login", "/register", "/css/**", "/js/**", "/images/**");
    }
}

如果你的项目权限规则比较复杂,也可以直接集成Spring Security做权限管控,默认就支持会话校验、登录跳转等能力。

内容的提问来源于stack exchange,提问作者aquile hollins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:06:05