gpt4 book ai didi

java - 使用 spring boot 和 thymeleaf 在 java 中将用户添加到数据库时出现问题

转载 作者:行者123 更新时间:2023-12-01 17:57:26 25 4
gpt4 key购买 nike

我正在使用本教程:spring boot CRUD application with tymeleaf

当我尝试拥有用户时出现问题,我收到此错误:

2020-03-15 09:51:09.413 ERROR 10168 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null 在 com.CRUD.CRUD_EXAMPLE.controller.UserController.addUser(UserController.java:33) ~[classes/:na]

代码如下:'''

    @Controller
public class UserController {
private UserRepository userRepository;
@GetMapping("/signup")
public String showSignUpForm(User user) {
return "add-user";
}

@PostMapping("/adduser")
public String addUser(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-user";
}


userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}

@GetMapping("/edit/{id}")
public String showUpdateForm(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));

model.addAttribute("user", user);
return "update-user";
}
@PostMapping("/update/{id}")
public String updateUser(@PathVariable("id") long id, @Valid User user,
BindingResult result, Model model) {
if (result.hasErrors()) {
user.setId(id);
return "update-user";
}

userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}

@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
userRepository.delete(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
}

'''

我的第 33 行是“userRepository.save(user)”;

最佳答案

请使用 @Repository 注释标记您的 UserRepository 实现 类,如下所示:

@Repository
public class UserRepositoryImpl implements UserRepository {

然后通过 Controller 中的 @Autowired 注释注入(inject)依赖项,如下所示:

@Controller
public class UserController {
private UserRepository userRepository;

@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}

这将修复您的 NullPointerException,因为 Spring 现在将为您创建并注入(inject)此依赖项。

关于java - 使用 spring boot 和 thymeleaf 在 java 中将用户添加到数据库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60691435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com