我不知道为什么提交注册表单(register.html)时registerSubmit函数没有运行,我的猜测是这与Spring Security的工作方式有关。即使尝试使用返回 View 的简单 Controller 方法,但根本没有执行,单击提交时我看到的只是同一页面。
RegisterController.java
@RequestMapping(value = {"/register"}, method = RequestMethod.POST)
public String registerSubmit(@Valid User user, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "register";
}
User userFound = userRepository.findByEmail(user.getEmail());
if (userFound != null)
{
System.out.println("User already in database");
return "register";
}
return "result";
}
注册.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Register Page</title>
</head>
<body>
<h1>Register page</h1>
<form action="#" th:action="@{/register}" th:object="${user}" method="post">
<table>
<tr>
<td> <label for="firstName">First name:</label> </td>
<td><input type="text" th:field="*{firstName}" id="firstName" /> </td>
<td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">firstName error</td>
</tr>
<tr>
<td><label for="lastName">Last name:</label> </td>
<td><input type="text" th:field="*{lastName}" id="lastName" /></td>
<td th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">lastName error</td>
</tr>
<tr>
<td><label for="email">email:</label> </td>
<td><input type="text" th:field="*{email}" id="email" /></td>
<td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">email error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
<a th:href="@{/login}">Login</a>
</body>
</html>
SecurityConfig.java,我已禁用 csrf 保护作为@M。 Deinum 建议,但这也不起作用。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user@mail.com"). password("{noop}pass").roles("USER");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers( "/register", "/login").permitAll()
.antMatchers("/result").permitAll()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.defaultSuccessUrl("/profile", true)
.permitAll()
.and()
.logout()
.permitAll();
}
}
最佳答案
Try by adding consuming data type to headers.
@RequestMapping(
value = "/register",
method = RequestMethod.POST,
headers="Accept=application/x-www-form-urlencoded")
public String registerSubmit(@Valid User user, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "register";
}.....
如果这不起作用,您可以使用 Postman 这样的工具发送请求,并通过调试服务器端代码找出接受的请求,从而找到有关错误的更多详细信息。如果 Spring Security 存在问题(例如 AuthenticationFailure),则应将错误记录在控制台中。
关于java - 为什么用户提交注册表单时没有执行registerSubmit? Spring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60382848/