Spring Boot结合JSTL(JSP页面)验证失效,错误消息显示哈希码
Hey Vikash, let's figure out why you're seeing that weird hash code (com.vikash.validator.UserValidator@6fec3d47) instead of your actual validation error messages. That's a common gotcha when working with Spring validation and JSPs—let's break this down step by step to fix it.
Why You're Seeing the Hash Code
The root issue here is that your JSP is outputting the UserValidator object itself instead of pulling the error messages from Spring's BindingResult. When you print a Java object directly in JSP without calling a method to get its string content, it defaults to calling toString(), which outputs the class name plus a hash code. That's exactly what you're seeing.
Step-by-Step Fixes
Let's go through each of your files to correct this:
1. Fix Your MainController.java
First, make sure your controller correctly handles validation and doesn't accidentally pass the UserValidator instance to the JSP model. Here's the right approach:
@Controller public class MainController { private final UserValidator userValidator; private final UserRepository userRepository; // Constructor injection (preferred over @Autowired) public MainController(UserValidator userValidator, UserRepository userRepository) { this.userValidator = userValidator; this.userRepository = userRepository; } @PostMapping("/submit-user") public String submitUser(@ModelAttribute("user") User user, BindingResult bindingResult) { // Run your custom validation userValidator.validate(user, bindingResult); // If there are errors, return to the form—DO NOT add the validator to the model! if (bindingResult.hasErrors()) { // ❌ Remove any line like model.addAttribute("validator", userValidator) return "user-form"; } // Save the valid user to the database userRepository.save(user); return "success"; } }
Critical Note: Never add the UserValidator object to your model. That's the most likely reason it's showing up as a hash code in your JSP.
2. Verify Your UserValidator.java
Ensure your validator properly implements Spring's Validator interface and adds errors to the Errors object (not returning messages directly):
@Component public class UserValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return User.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; // Validate the username field if (user.getUsername() == null || user.getUsername().trim().isEmpty()) { errors.rejectValue( "username", "username.empty", "Username cannot be empty" ); } else if (user.getUsername().length() < 5) { errors.rejectValue( "username", "username.too.short", "Username must be at least 5 characters long" ); } } }
Here, we use errors.rejectValue() to bind error messages directly to the username field, so Spring's BindingResult can track them properly.
3. Correct Your JSP Page
This is where the magic happens—make sure you're pulling errors from the BindingResult instead of referencing the validator object. Use Spring's form tags for simplicity:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>User Form</title> <style>.error { color: red; }</style> </head> <body> <h1>Create User</h1> <form:form modelAttribute="user" action="/submit-user" method="post"> <div> <label for="username">Username:</label> <form:input path="username" id="username"/> <!-- Display errors for the username field --> <form:errors path="username" cssClass="error"/> </div> <button type="submit">Submit</button> </form:form> </body> </html>
Common Mistake to Fix: If your JSP has any code like ${validator} or references the validator object directly, delete it immediately. That's what's causing the hash code to show up.
4. Double-Check pom.xml Dependencies
Make sure you have all required dependencies for Spring validation and JSP support:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <!-- JSP & JSTL for Spring Boot --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> </dependencies>
Quick Troubleshooting Checklist
- Remove any references to
UserValidatorin your controller's model - Confirm your validator uses
errors.rejectValue()to attach messages to fields - Ensure your JSP uses
form:errors path="username"(or pulls fromBindingResult) instead of referencing the validator - Verify you have all required dependencies in
pom.xml
Once you apply these fixes, you should see your actual validation messages instead of that confusing hash code. Let me know if you hit any snags with the code!
内容的提问来源于stack exchange,提问作者Vikash

