当我用一些id输入users/update/{id}时,例如id = 6,我得到的是"Resolved [org.springframework.web]。HttpRequestMethodNotSupportedException:请求方法'POST'不支持]"。
基本上,我的目的是当我在URL (users/update/{id})是:
- 方法updateUser()由上述URL触发,从存储库中检索id = 6的用户 从id = 6的用户中创建viewModel
- 将这个viewModel传递给HTML模板"registration-formUpdate"作为一个"用户"
<form class="form-horizontal" method="post" th:href="@{~/registration}" th:object="${user}">
中的对象 - ,然后将该对象传递给端点"/registration"和registrationUsersAdding()"方法,以自动使用从存储库 检索到的用户值填充表单。
- 通过点击"按钮上的registration-formUpdate"模板保存更新后的用户到数据库
但是,当我点击"按钮,我得到405状态和"Resolved [org.springframework.web。HttpRequestMethodNotSupportedException:请求方法'POST'不支持]">
如果我的解释不那么好,我很抱歉,我正在学习春天,英语不是我的第一语言。我已经这样做了3-4次在不同的应用程序之前,它总是工作,在同一个项目中,我有事件类与不同的实体,但相同的逻辑和它的作品。我不知道为什么这里没有。 控制器类
@RequiredArgsConstructor
@Controller
public class RegistrationController {
private final UserService userService;
private final UserRepository userRepository;
@PostMapping("/registration")
public String registrationUsersAdding(@ModelAttribute("user") @Valid UserViewModel user2,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
if (user2.getId() == null) {
return "registration-form";
} else {
return "registration-formUpdate";
}
} else {
if (user2.getId() == null) {
userService.add(user2);
} else {
userService.update(user2);
}
}
return "redirect:/login";
}
@Secured("ROLE_ADMIN")
@GetMapping("users/update/{id}")//toooooooo
public String updateUser(@PathVariable(value = "id") Long id, Model model) {
var user = userService.userToViewModel(userRepository.getOne(id));
model.addAttribute("user", user);
return "registration-formUpdate";
}
}
服务类
@Service
@RequiredArgsConstructor
public class UserService implements AddUpdateGetDeleteUser {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final PasswordEncoder passwordEncoder;
public void add(UserViewModel userViewModel) {
List<Role> roles;
Role role = new Role();
role.setType(RoleType.valueOf(userViewModel.getRoles()));// pomyslec nad tym
roleRepository.save(role);
roles = Collections.singletonList(role);
User user1 = User.builder()
.firstName(userViewModel.getFirstName())
.lastName(userViewModel.getLastName())
.login(userViewModel.getLogin())
.password(passwordEncoder.encode(userViewModel.getPassword()))
.email(userViewModel.getEmail())
.roles(roles)
.build();
userRepository.save(user1);
}
public void update(UserViewModel userDto) {
Optional<User> optionalUser = userRepository.findById(userDto.getId());
if (optionalUser.isPresent()) {
User user = optionalUser.get();
user.setId(userDto.getId());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setRoles(Collections.singletonList(GetRole(userDto.getRoles())));
user.setLogin(userDto.getLogin());
user.setEmail(userDto.getEmail());
user.setPassword(passwordEncoder.encode(userDto.getPassword()));
userRepository.save(user);
}
}
public UserViewModel userToViewModel(User user) {
return UserViewModel.builder()
.id(user.getId())
.firstName(user.getFirstName())
.lastName(user.getLastName())
.roles(user.getRoles().get(0).toString())
.login(user.getLogin())
.email(user.getEmail())
.password(passwordEncoder.encode(user.getPassword()))
.build();
}
private Role GetRole(String roleType) {
var role = new Role();
role.setType(RoleType.valueOf(roleType));
return role;
}
}
日志
2022-12-30 00:35:43.807 INFO 5804 --- [ main] Z.Z.ZadanieRekrutacyjneApplication : Started ZadanieRekrutacyjneApplication in 10.364 seconds (JVM running for 11.253)
2022-12-30 00:36:28.052 INFO 5804 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-30 00:36:28.052 INFO 5804 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-12-30 00:36:28.055 INFO 5804 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
2022-12-30 00:36:28.527 WARN 5804 --- [nio-8080-exec-1] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [387] milliseconds.
2022-12-30 00:37:13.180 WARN 5804 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
2022-12-30 00:42:59.615 INFO 5804 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2022-12-30 00:42:59.621 INFO 5804 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-12-30 00:42:59.624 INFO 5804 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-12-30 00:42:59.646 INFO 5804 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
现在ok了,在update-form html模板中从class="form-horizontal" method="post" th:href="@{~/registration}" th:object="${user}">
更改为<form action="#" method="POST" th:action="@{~/registration}" th:object="${user}">
,它工作