问题:在使用Spring Boot与Thymeleaf的Java中将用户添加到数据库时出现错误。

huangapple go评论81阅读模式
英文:

Problem adding user to database in java using spring boot with thymeleaf

问题

我正在使用这个教程:使用Thymeleaf的Spring Boot CRUD应用

当我尝试添加用户时出现了问题,我得到了以下错误:

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
	at 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);

英文:

I was using this tutorial : spring boot CRUD application with tymeleaf

The problem happen when I try to had a user, I got this error :

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
at com.CRUD.CRUD_EXAMPLE.controller.UserController.addUser(UserController.java:33) ~[classes/:na]

Here's the code :
'''

    @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";
}
}

'''

My line 33 is 'userRepository.save(user)';

答案1

得分: 0

根据所说,传递给该方法的 User user 对象为 null,或者其字段之一为 null。确保该对象包含来自视图的所有数据。
还要检查您的 HTML 文件中的所有字段是否正确映射到 User 对象的字段。

英文:

As it says you, The object User user that comes to the method is null, or one of its field is null.
Make sure that this objects contains all data coming from view.
Check also if all the field in your html file are well mapped to the field of the User object.

答案2

得分: 0

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

@Repository
public class UserRepositoryImpl implements UserRepository {

然后在您的控制器中使用 @Autowired 注解注入依赖,如下所示:

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

这将修复您的 NullPointerException,因为Spring现在会为您创建并注入这个依赖项。

英文:

Please mark your UserRepository implementation class with the @Repository annotation, like this:

@Repository
public class UserRepositoryImpl implements UserRepository {

Then inject the dependency via the @Autowired annotation in your controller like this:

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

This will fix your NullPointerException, because Spring will now create and inject this dependency for you.

huangapple
  • 本文由 发表于 2020年3月15日 17:28:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/60691435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定