Moved MVC Custom Valitation article code from spring-mvc-java to spring-mvc-basics module

This commit is contained in:
Gerardo Roza 2019-07-01 19:35:33 -03:00
parent e84ea4d4c5
commit e77faf8d99
13 changed files with 207 additions and 207 deletions

View File

@ -13,3 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings)
- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml)
- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts)
- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator)

View File

@ -11,7 +11,7 @@ import javax.validation.Payload;
@Documented @Documented
@Constraint(validatedBy = ContactNumberValidator.class) @Constraint(validatedBy = ContactNumberValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD}) @Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberConstraint { public @interface ContactNumberConstraint {

View File

@ -2,10 +2,7 @@ package com.baeldung.model;
import com.baeldung.customvalidator.FieldsValueMatch; import com.baeldung.customvalidator.FieldsValueMatch;
@FieldsValueMatch.List({ @FieldsValueMatch.List({ @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") })
@FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"),
@FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!")
})
public class NewUserForm { public class NewUserForm {
private String email; private String email;
private String verifyEmail; private String verifyEmail;

View File

@ -1,13 +1,14 @@
package com.baeldung.web.controller; package com.baeldung.web.controller;
import com.baeldung.model.ValidatedPhone; import javax.validation.Valid;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid; import com.baeldung.model.ValidatedPhone;
@Controller @Controller
public class ValidatedPhoneController { public class ValidatedPhoneController {
@ -28,5 +29,4 @@ public class ValidatedPhoneController {
return "phoneHome"; return "phoneHome";
} }
} }

View File

@ -24,7 +24,7 @@
<h2>Phone Number</h2> <h2>Phone Number</h2>
<c:if test="${not empty message}"><div class="message green">${message}</div></c:if> <c:if test="${not empty message}"><div class="message green">${message}</div></c:if>
<form:form action="/spring-mvc-java/addValidatePhone" modelAttribute="validatedPhone"> <form:form action="/spring-mvc-basics/addValidatePhone" modelAttribute="validatedPhone">
<label for="phoneInput">Phone: </label> <label for="phoneInput">Phone: </label>
<form:input path="phone" id="phoneInput" /> <form:input path="phone" id="phoneInput" />

View File

@ -5,46 +5,47 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
public class ClassValidationMvcIntegrationTest { public class ClassValidationMvcIntegrationTest {
private MockMvc mockMvc; private MockMvc mockMvc;
@Before @BeforeEach
public void setup(){ public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()).build(); this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController())
.build();
} }
@Test @Test
public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/user") this.mockMvc.perform(MockMvcRequestBuilders.post("/user")
.accept(MediaType.TEXT_HTML) .accept(MediaType.TEXT_HTML)
.param("email", "john@yahoo.com") .param("email", "john@yahoo.com")
.param("verifyEmail", "john@yahoo.com") .param("verifyEmail", "john@yahoo.com")
.param("password", "pass") .param("password", "pass")
.param("verifyPassword", "pass")) .param("verifyPassword", "pass"))
.andExpect(model().attribute("message", "Valid form")) .andExpect(model().attribute("message", "Valid form"))
.andExpect(view().name("userHome")) .andExpect(view().name("userHome"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andDo(print()); .andDo(print());
} }
@Test @Test
public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/user") this.mockMvc.perform(MockMvcRequestBuilders.post("/user")
.accept(MediaType.TEXT_HTML) .accept(MediaType.TEXT_HTML)
.param("email", "john@yahoo.com") .param("email", "john@yahoo.com")
.param("verifyEmail", "john@yahoo.commmm") .param("verifyEmail", "john@yahoo.commmm")
.param("password", "pass") .param("password", "pass")
.param("verifyPassword", "passsss")) .param("verifyPassword", "passsss"))
.andExpect(model().errorCount(2)) .andExpect(model().errorCount(2))
.andExpect(view().name("userHome")) .andExpect(view().name("userHome"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andDo(print()); .andDo(print());
} }
} }

View File

@ -6,8 +6,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -17,25 +17,27 @@ public class CustomMVCValidatorIntegrationTest {
private MockMvc mockMvc; private MockMvc mockMvc;
@Before @BeforeEach
public void setup(){ public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()).build(); this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController())
.build();
} }
@Test @Test
public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception{ public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception {
this.mockMvc.perform(get("/validatePhone")).andExpect(view().name("phoneHome")); this.mockMvc.perform(get("/validatePhone"))
.andExpect(view().name("phoneHome"));
} }
@Test @Test
public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone"). this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone")
accept(MediaType.TEXT_HTML). .accept(MediaType.TEXT_HTML)
param("phoneInput", "123")). .param("phoneInput", "123"))
andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone","ContactNumberConstraint")). .andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone", "ContactNumberConstraint"))
andExpect(view().name("phoneHome")). .andExpect(view().name("phoneHome"))
andExpect(status().isOk()). .andExpect(status().isOk())
andDo(print()); .andDo(print());
} }
} }

View File

@ -16,7 +16,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring)
- [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit)
- [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files)
- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator)
- [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config)
- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable)
- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation)