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

Spring Security+Thymeleaf二次登录触发TemplateInputException异常如何解决

问题根因与修复方案

核心根因

  1. 控制器请求处理方法访问修饰符错误
  2. 登录失败配置使用内部转发导致响应提前提交
  3. Spring Security与Thymeleaf安全方言的上下文初始化时序冲突

修复步骤

第一步:修正LoginController方法修饰符

Spring MVC要求控制器的请求映射方法必须为public,私有方法会导致Spring反射调用失败,是触发模板解析异常的直接原因。
修改后代码:

@Controller
public class LoginController {
    // 把private改为public
    @GetMapping("/login")
    public String loginRender(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken){
            return "login";
        }else {
            return "redirect:/";
        }
    }
}

第二步:修改登录失败跳转配置

你当前使用的failureForwardUrl是服务器内部转发,登录认证失败时Spring Security已经向响应写入了部分内容,再转发到/login页会触发响应已提交的错误,和你的报错日志完全匹配。
将failureForwardUrl改为failureUrl使用重定向跳转:

.formLogin()
    .loginPage("/login")
    .usernameParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY)
    .passwordParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY)
    .defaultSuccessUrl("/user/profile")
    // 替换failureForwardUrl为failureUrl
    .failureUrl("/login?error")

第三步:检查Thymeleaf安全方言依赖

确保你引入了和Spring Security版本匹配的Thymeleaf安全扩展依赖,避免属性解析异常:
Maven配置示例(对应Spring Security 5.x):

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

可选优化

你可以移除控制器里的登录状态判断逻辑,直接在Spring Security配置中添加已登录用户访问登录页的跳转规则,减少手动上下文获取的时序问题:

.formLogin()
    .loginPage("/login")
    // 已登录用户访问登录页直接跳转到个人页
    .defaultSuccessUrl("/user/profile", true)
    .permitAll()

修复后二次登录时会正常生成新的JSESSIONID Cookie,sec:authorize属性也会正常解析,不会再抛出模板解析异常。

内容的提问来源于stack exchange,提问作者Alexandar Dimov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:45:04