I had the following setup:
IndexCntl.java (Controller):
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, ModelMap map) {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
map.addAttribute("serverTime", formattedDate );
map.addAttribute("email", new Email());
Map sexoOpts = new HashMap();
sexoOpts.put("M", "Homem");
sexoOpts.put("F", "Mulher");
map.addAttribute("sexoList", sexoOpts);
return "index";
}
@RequestMapping(value = "/save-email", method = RequestMethod.POST)
public String doSaveEmail(@Valid @ModelAttribute("email") Email email, Model model, BindingResult result){
log.info("Email debug: "+email.getEmail()+" "+email.getMysexy()+" "+email.getWantedsexy());
if (result.hasErrors()){
log.info("Entrou result.hasError()");
return "index";
}
Date date = new Date();
email.setCreationDate(date);
try{
emailBo.saveEmail(email);
}catch(Exception e){
e.printStackTrace();
}
model.addAttribute("email", new Email());
return "index";
}
index.jsp (view):
<form:form action="save-email" method="POST" modelAttribute="email" cssStyle="display:-webkit-box">
<form:select path="mysexy" cssStyle="width:120px;">
<form:option value="" label="- Sou -"/>
<form:options items="${sexoList}" />
</form:select>
<form:errors path="mysexy" cssClass="errors"/>
<form:select path="wantedsexy" cssStyle="width:120px;">
<form:option value="" label="- Busco -"/>
<form:options items="${sexoList}" />
</form:select>
<form:errors path="wantedsexy" cssClass="errors"/>
<br/>
<form:errors path="wantedsexy" cssClass="errors"/>
<div class="input-append">
<input type="text" id="email" name="email" size="30" maxlength="30" placeholder="E-mail" class=""/>
<form:errors path="email" cssClass="errors"/>
<input id="btncadastrar" class="btn btn-block btn-primary" type="submit" value="Cadastrar E-mail"/>
</div>
</form:form>
and part of the model Email.java:
@Document
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Email extends BaseBean {
// @Pattern(regexp =
// "^[\\w\\-]+(\\.[\\w\\-]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$",
// message="E-mail com formato incorreto.")
@NotNull(message = "Não pode ser vazio")
@NotEmpty(message = "Não pode ser vazio-nulo")
@org.hibernate.validator.constraints.Email(message = "E-mail inválido")
private String email;
@NotEmpty(message = "Informe ao menos um valor")
private String mysexy;
@NotEmpty(message = "Informe ao menos um valor")
private String wantedsexy;
and i'm receiving this error when i try to pass with a empty email in input:
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'email' on field 'email': rejected value []; codes [NotEmpty.email.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [email.email,email]; arguments []; default message [email]]; default message [Não pode ser vazio-nulo]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'email' on field 'email': rejected value []; codes [NotEmpty.email.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [email.email,email]; arguments []; default message [email]]; default message [Não pode ser vazio-nulo]
org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:110)
what can be wrong in my setup???
You explicit forbid empty values:
@NotNull(message = "Não pode ser vazio")
--> @NotEmpty(message = "Não pode ser vazio-nulo")
@org.hibernate.validator.constraints.Email(message = "E-mail inválido")
private String email;
Hibernate validate the entity before saving or update, and your entity fails.
You can disable this validation in you persistence.xml
file configuration.
<persistence ...>
<persistence-unit ...>
...
<properties>
<property name="javax.persistence.validation.mode" value="none"/>
</properties>
</persistence-unit>
</persistence>
If you want to check only some validation rules, then you can use "Validation Groupes"
If your problem is that the controller method is not invoked, then it is because of the @Valid
annotation for Email
. If you want to have a controller method to be invoked event if a parameter with @Valid
annotaton is not valid, then you need a parameter of type BindingResult
DIRECTLY AFTER that parameter
public String doSaveEmail(@Valid @ModelAttribute("email") Email email, BindingResult resultForEmail, Model model, BindingResult resultForModel)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.