问题
I am using Spring-MVC and I would like to do validation tests in backend. Currently I am able to perform the tests, redirect properly to the link. But I am only unable to add custom error messages incase there is a problem, Example : "Firstname is empty". I tried using the ValidationMessages_en_EN.properties file in WEB-INF, but that also didn't help. I am posting my code, kindly let me know where I am going wrong :
COntroller :
@Controller
public class PersonController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String listPersons(Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
if(!(person==null)){
return "redirect:/canvas/list";
} else {
model.addAttribute("person", new Person());
// model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("notices",new Notes());
model.addAttribute("canvases",new Canvas());
return "person";
}
}
@RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(@Valid Person person,BindingResult bindingResult,@ModelAttribute("person") Person p,Model model){
if(bindingResult.hasErrors()){
return "redirect:/";
}
this.personService.addPerson(p);
return "redirect:/";
}
Entity :
@Entity
@Table(name="person")
public class Person implements UserDetails{
private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
@SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
private int id;
@Valid
@NotEmpty @Email(message = "username.empty")
@Column(name = "username")
private String username;
@NotEmpty
@Column(name = "password")
private String password;
@Valid
@Size(min = 2,max = 30,message = "firstName.empty")
@Column(name = "firstname")
private String firstName;
@Valid
@Size(min = 2,max = 50)
@Column(name = "secretquestion")
private String secretquestion;
@Valid
@Size(min = 2,max = 500,message = "secretanswer.empty")
@Column(name = "secretanswer")
private String secretanswer;
Servlet-Context.xml
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="ValidatorMessages_en_EN.properties"/>
</beans:bean>
JSP/HTML :
<c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person" method="post">
<table>
<c:if test="${!empty person.username}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="firstName">
<spring:message text="FirstName"/>
</form:label>
</td>
<td>
<form:input path="firstName" />
</td>
<td><form:errors path="firstName"/>
</tr>
<tr>
<td>
<form:label path="username">
<spring:message text="Email"/>
</form:label>
</td>
<td>
<form:input path="username" />
</td>
<td><form:errors path="username"/>
</tr>
<tr>
<td>
<form:label path="password">
<spring:message text="Password"/>
</form:label>
</td>
<td>
<form:input path="password" />
</td>
<td><form:errors path="Password"/>
</tr>
<tr>
<td>
<form:label path="secretquestion">
<spring:message text="secretquestion"/>
</form:label>
</td>
<td>
<form:input path="secretquestion" />
</td>
<td><form:errors path="secretquestion"/>
</tr>
<tr>
<td>
<form:label path="secretanswer">
<spring:message text="secretanswer"/>
</form:label>
</td>
<td>
<form:input path="secretanswer" />
</td>
<td><form:errors path="secretanswer"/>
</tr>
POM.xml :
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
Messages.properties :
firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!
Messages_en_US.properties
firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!
回答1:
<spring:message text="FirstName"/>
Should be like <spring:message code="FirstName"/>
try to replace text to code in your <spring:message />
tag
and change basename value to ValidatorMessages and en_US
Spring will append for you
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="ValidatorMessages"/>
</beans:bean>
sava your file as ValidatorMessages_en_US.properties
in your resource
folder
回答2:
@ExceptionHandler(Exception.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public Response handleException(Exception e) {
Response response = new Response();
if(e instanceof MethodArgumentNotValidException ){
MethodArgumentNotValidException methodException = (MethodArgumentNotValidException)e;
BindingResult bindingResult =methodException.getBindingResult();
if(bindingResult!=null && bindingResult.hasErrors()){
List<FieldError> fieldErrorList= bindingResult.getFieldErrors();
for(FieldError fieldError: fieldErrorList ){
response.adderror(fieldError.getDefaultMessage());
}
}
}
return response;
}
来源:https://stackoverflow.com/questions/27017029/adding-custom-error-messages-for-validation-in-spring-mvc