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

Spring整合MySQL开发登录系统时@PostMapping请求无响应问题排查

问题原因

  • 项目引入Spring Security依赖后,框架默认会拦截/login路径的POST请求,走自带的身份校验逻辑,请求根本不会转发到你自定义的@PostMapping接口,这是接口无法触发的核心原因
  • 就算绕过Spring Security拦截,控制器POST方法的@ModelAttribute("user")和前端表单th:object="${login}"绑定的参数名不一致,也无法正常接收提交的用户信息
  • 密码输入框用了type="text",输入内容会明文显示,存在安全隐患

解决方案

  1. 新增/修改Spring Security配置类,放行登录相关请求、关闭默认表单登录和csrf校验(测试阶段可这么配置,上线前按需调整csrf策略)
    示例配置代码:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 关闭csrf校验,避免POST请求被拦截
            .csrf().disable()
            // 关闭Spring Security默认的表单登录
            .formLogin().disable()
            .authorizeRequests()
            // 放行登录、注册、静态资源路径,不需要登录就能访问
            .antMatchers("/login", "/register", "/css/**", "/images/**").permitAll()
            // 其余路径需要登录后访问
            .anyRequest().authenticated();
    }
}
  1. 修改Login控制器的POST方法参数,把@ModelAttribute("user")改成@ModelAttribute("login"),和前端表单绑定的参数名对齐:
@PostMapping
public String login(@ModelAttribute("login") User user) {
    // 原有逻辑保持不变
}
  1. 修改login.html里的密码输入框类型,把type="text"改成type="password":
<input type="password" class="form-control" name="password" th:field="*{password}" required="required">

后续优化建议

不要明文存储用户密码,注册时用BCryptPasswordEncoder加密后再存入数据库,登录时把用户输入的密码加密后再和数据库存储的密文对比,避免密码泄露风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:15:02