我正在尝试使用 HTML 表单将数据提交到我的 Spring/Thymeleaf 服务器。当我使用 POST 方法提交时,会使用相同的 URL 发送第二个请求,但带有附加的“?error”查询参数和 GET 方法。此后续请求会导致错误,因为它不携带 POST 请求正文中存在的信息,并且我需要以某种方式处理第二个请求。在我的检查器窗口中,它显示第二个请求是由第一个请求以某种方式发起的。
将方法更改为 GET 后,请求可以完美运行。不过,此解决方案对我不起作用,因为我正在使用表单提交密码数据。
这是导致问题的表单(类等省略):
<form action="/login" method="POST">
<div>
<div>
<span><i></i></span>
</div>
<input name="username" type="text" placeholder="username">
</div>
<div>
<div>
<span><i></i></span>
</div>
<input name="password" type="password" placeholder="password">
</div>
<input type="hidden" th:value="${_csrf.token}" th:name="${_csrf.parameterName}">
<div>
<input type="submit" value="Login" name="button">
</div>
</form>
这是处理所有/login 请求的 Controller (这还没有完成,但我可能在这里遗漏了一些重要的东西):
@Controller()
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String doGet() {
System.out.println("Login page accessed");
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doPost() {
System.out.println("Login attempted");
return "redirect:home";
}
}
提交表单时的预期输出是“已尝试登录”,但唯一的结果是“已访问登录页面”。
这是安全配置方法,它显式定义了此端点的一些额外功能
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/about", "/login", "/css/**", "/js/**", "/assets/**" ).permitAll()
.anyRequest().permitAll()
.and()
.csrf()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/home")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutUrl("/logout")
.addLogoutHandler( new CookieClearingLogoutHandler() );
}
第一个请求似乎甚至没有到达 Controller 。如何避免发送第二个请求?
最佳答案
每当发生登录失败时,Spring Security 都会启动额外的 /login?error
调用。这是默认表单登录 authenticationFailureUrl
。
Spring Security 有一个默认的 /login
POST 处理程序,并且您的代码可能与它冲突(即,您的表单发布数据进入 Spring Security 的处理程序而不是您的处理程序,然后在那里验证失败并导致重定向到错误)。
您可能想查看 DaoAuthenticationProvider
和 CustomAuthenticationProvider
。
关于java - 表单提交发送不需要的 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56071273/