Spring MVC用户注册时出现NullPointerException问题求助
Hey there, let's break down why you're hitting this NullPointerException in your updateUser method and fix it up.
问题根源分析
The error points directly to line 83: u.setUsername(user.getUsername()) — this means the variable u is null. Looking at the line right above it:
User u = userRepository.findByEmail(user.getEmail());
So userRepository.findByEmail(user.getEmail()) is returning null. This can happen for two key reasons:
- The email value from your incoming
userobject doesn't match any email in your H2 database (double-check if you're passing an existing email likesauron@mordor.comwithout typos or extra spaces). - The incoming
userobject has anullemail (make sure your frontend is correctly sending the email field, or add checks to ensure it's not empty).
修复方案
Here are concrete, actionable steps to fix this and make your code more robust:
1. Add null safety checks for the fetched user
First, handle the case where no user is found by email to avoid the NPE entirely:
public User updateUser(User user) throws UserServiceException { // First validate incoming user data if (user == null || user.getEmail() == null || user.getEmail().trim().isEmpty()) { throw new UserServiceException("User email cannot be null or empty"); } if (user.getEncryptedPassword() == null || user.getEncryptedPassword().trim().isEmpty()) { throw new UserServiceException("Password cannot be null or empty"); } User u = userRepository.findByEmail(user.getEmail()); if (u == null) { throw new UserServiceException("No user found with email: " + user.getEmail()); } // Update the existing user's fields u.setUsername(user.getUsername()); u.setEncryptedPassword(passwordEncoder.encode(user.getEncryptedPassword())); return userRepository.save(u); }
Note: I adjusted the password update to set it on u (the existing user pulled from the database) instead of the incoming user object — since you're saving u, that's where all updated values should go.
2. Verify your request data
Make sure the registration request is sending a valid email that exists in your H2 database. For example, if you're testing with aragorn@endor.com, confirm the request body includes this exact email string (no typos, missing domains, etc.).
3. Add input validation (optional but highly recommended)
Add validation annotations to your User entity/DTO to enforce required fields upfront:
public class User { @NotNull(message = "Email cannot be null") @NotEmpty(message = "Email cannot be empty") private String email; @NotNull(message = "Password cannot be null") @NotEmpty(message = "Password cannot be empty") private String encryptedPassword; // Other fields, getters, and setters }
Then enable validation in your controller by adding @Valid to the request parameter, so invalid data gets rejected early.
额外检查
Double-check your UserRepository implementation. If you're using Spring Data JPA, the method signature should look like this to correctly query the H2 USERS table:
public interface UserRepository extends JpaRepository<User, Long> { User findByEmail(String email); }
内容的提问来源于stack exchange,提问作者Audiosleef

