Parcourir la source

4th labs: form validation

m_sudra il y a 3 ans
Parent
commit
065ee27fda

+ 10 - 0
wpfat_exercises/pom.xml

@@ -56,6 +56,16 @@
             <artifactId>commons-dbcp2</artifactId>
             <version>2.9.0</version>
         </dependency>
+        <dependency>
+            <groupId>commons-validator</groupId>
+            <artifactId>commons-validator</artifactId>
+            <version>1.7</version>
+        </dependency>
+        <dependency>
+            <groupId>org.hibernate</groupId>
+            <artifactId>hibernate-validator</artifactId>
+            <version>8.0.0.Final</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 15 - 0
wpfat_exercises/src/main/java/pl/sudra/configuration/SpringConfiguration.java

@@ -5,9 +5,11 @@ import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.support.ReloadableResourceBundleMessageSource;
+import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
 import org.springframework.web.servlet.LocaleResolver;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 import org.springframework.web.servlet.i18n.CookieLocaleResolver;
 import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@@ -51,4 +53,17 @@ public class SpringConfiguration implements WebMvcConfigurer {
         interceptor.setParamName("lang");
         registry.addInterceptor(interceptor);
     }
+
+    @Override
+    public void addResourceHandlers(ResourceHandlerRegistry registry) {
+        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
+    }
+
+    @Bean
+    @Override
+    public LocalValidatorFactoryBean getValidator() {
+        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
+        bean.setValidationMessageSource(messageSource());
+        return bean;
+    }
 }

+ 16 - 6
wpfat_exercises/src/main/java/pl/sudra/controller/AppUserController.java

@@ -1,9 +1,11 @@
 package pl.sudra.controller;
 
 import jakarta.servlet.http.HttpServletRequest;
+import jakarta.validation.Valid;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
+import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.ServletRequestUtils;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -11,9 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import pl.sudra.domain.AppUser;
 import pl.sudra.service.AppUserService;
+import pl.sudra.validator.AppUserValidator;
 
 @Controller
 public class AppUserController {
+    private AppUserValidator appUserValidator = new AppUserValidator();
 
     private AppUserService appUserService;
 
@@ -34,18 +38,24 @@ public class AppUserController {
     }
 
     @RequestMapping(value = "/addAppUser", method = RequestMethod.POST)
-    public String addAppUser(@ModelAttribute("appUser") AppUser appUser) {
+    public String addAppUser(@Valid @ModelAttribute("appUser") AppUser appUser, BindingResult result, Model model) {
 
         System.out.println("First Name: " + appUser.getFirstName() +
                 " Last Name: " + appUser.getLastName() + " Tel.: " +
                 appUser.getTelephone() + " Email: " + appUser.getEmail());
 
-        if (appUser.getId() == 0)
-            appUserService.addAppUser(appUser);
-        else
-            appUserService.editAppUser(appUser);
+        appUserValidator.validate(appUser, result);
+        if (result.getErrorCount() == 0) {
+            if (appUser.getId() == 0)
+                appUserService.addAppUser(appUser);
+            else
+                appUserService.editAppUser(appUser);
 
-        return "redirect:appUsers";
+            return "redirect:appUsers";
+        }
+
+        model.addAttribute("appUserList", appUserService.listAppUser());
+        return "appUser";
     }
 
     @RequestMapping("/delete/{appUserId}")

+ 8 - 0
wpfat_exercises/src/main/java/pl/sudra/domain/AppUser.java

@@ -1,6 +1,8 @@
 package pl.sudra.domain;
 
 import jakarta.persistence.*;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
 
 @Entity
 @Table(name = "appUser")
@@ -9,10 +11,16 @@ public class AppUser {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     long id;
+    @NotNull
     @Column(name = "firstName", nullable = false)
+    @Size(min = 2, max = 30, message = "{error.size.firstName}")
     private String firstName;
+    @NotNull
+    @Size(min = 2, max = 30)
     private String lastName;
+    @NotNull
     private String email;
+    @Size(min = 9, max = 9)
     private String telephone;
 
     public long getId() {

+ 31 - 0
wpfat_exercises/src/main/java/pl/sudra/validator/AppUserValidator.java

@@ -0,0 +1,31 @@
+package pl.sudra.validator;
+
+import org.apache.commons.validator.routines.EmailValidator;
+import org.springframework.util.StringUtils;
+import org.springframework.validation.Errors;
+import org.springframework.validation.ValidationUtils;
+import org.springframework.validation.Validator;
+import pl.sudra.domain.AppUser;
+
+public class AppUserValidator implements Validator {
+    EmailValidator emailValidator = EmailValidator.getInstance();
+
+    @Override
+    public boolean supports(Class clazz) {
+        return AppUser.class.isAssignableFrom(clazz);
+    }
+
+    @Override
+    public void validate(Object arg0, Errors errors) {
+        ValidationUtils.rejectIfEmpty(errors, "firstName", "error.field.required");
+        ValidationUtils.rejectIfEmpty(errors, "lastName", "error.field.required");
+        ValidationUtils.rejectIfEmpty(errors, "telephone", "error.field.required");
+        ValidationUtils.rejectIfEmpty(errors, "email", "error.field.required");
+
+        if (errors.getErrorCount() == 0) {
+            if (StringUtils.hasText(((AppUser) arg0).getEmail()) && !emailValidator.isValid(((AppUser) arg0).getEmail())) {
+                errors.rejectValue("email", "error.email.invalid");
+            }
+        }
+    }
+}

+ 35 - 31
wpfat_exercises/src/main/webapp/appUser.jsp

@@ -17,37 +17,41 @@
 
 <h1>App user info:</h1>
 <form:form method="post" action="addAppUser" modelAttribute="appUser">
-    <table>
-        <tr>
-            <td><form:hidden path="id"/>
-        </tr>
-        <tr>
-            <td><form:label path="firstName"><spring:message code="label.firstName"/></form:label></td>
-            <td><form:input path="firstName"/></td>
-        </tr>
-        <tr>
-            <td><form:label path="lastName"><spring:message code="label.lastName"/></form:label></td>
-            <td><form:input path="lastName"/></td>
-        </tr>
-        <tr>
-            <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
-            <td><form:input path="email"/></td>
-        </tr>
-        <tr>
-            <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
-            <td><form:input path="telephone"/></td>
-        </tr>
-        <tr>
-            <td colspan="2">
-                <c:if test="${appUser.id==0}">
-                    <input type="submit" value="<spring:message code="label.addAppUser"/>"/>
-                </c:if>
-                <c:if test="${appUser.id!=0}">
-                    <input type="submit" value="<spring:message code="label.editAppUser"/>"/>
-                </c:if>
-            </td>
-        </tr>
-    </table>
+<table>
+    <tr>
+        <td><form:hidden path="id"/>
+    </tr>
+    <tr>
+        <td><form:label path="firstName"><spring:message code="label.firstName"/></form:label></td>
+        <td><form:input path="firstName"/></td>
+        <td><form:errors path="firstName"/></td>
+    </tr>
+    <tr>
+        <td><form:label path="lastName"><spring:message code="label.lastName"/></form:label></td>
+        <td><form:input path="lastName"/></td>
+        <td><form:errors path="lastName"/></td>
+    </tr>
+    <tr>
+        <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
+        <td><form:input path="email"/></td>
+        <td><form:errors path="email"/></td>
+    </tr>
+    <tr>
+        <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
+        <td><form:input path="telephone"/></td>
+        <td><form:errors path="telephone"/></td>
+    </tr>
+    <tr>
+        <td colspan="2">
+            <c:if test="${appUser.id==0}">
+                <input type="submit" value="<spring:message code="label.addAppUser"/>"/>
+            </c:if>
+            <c:if test="${appUser.id!=0}">
+                <input type="submit" value="<spring:message code="label.editAppUser"/>"/>
+            </c:if>
+        </td>
+    </tr>
+</table>
 </form:form>
 
 <h3><spring:message code="label.userList"/></h3>

+ 5 - 0
wpfat_exercises/src/main/webapp/resources/i18n/messages_de.properties

@@ -5,3 +5,8 @@ label.telephone     =   Telefon
 label.addAppUser    =   Benutzer hinzuf&#252;gen
 label.userList      =   Liste der App Benutzer
 label.editAppUser   =   Benutzer bearbeiten
+
+error.field.required=   Feld ist obligatorisch
+error.email.invalid =   Falsche E-Mail-Adresse
+error.size.firstName=   Die Großße muss zwischen {min} und {max} liegen.
+# in einer alteren Version der Bibliotek {2} und {1}

+ 6 - 1
wpfat_exercises/src/main/webapp/resources/i18n/messages_en.properties

@@ -4,4 +4,9 @@ label.email         =   Email
 label.telephone     =   Telephone
 label.addAppUser    =   Add App User
 label.editAppUser   =   Edit App User
-label.userList      =   List of App Users
+label.userList      =   List of App Users
+
+error.field.required=   Field is required
+error.email.invalid =   Invalid email
+error.size.firstName=   Size must be between {min} and {max}.
+# in older library version {2} and {1}

+ 6 - 1
wpfat_exercises/src/main/webapp/resources/i18n/messages_pl.properties

@@ -4,4 +4,9 @@ label.email         =   Email
 label.telephone     =   Telefon
 label.addAppUser    =   Dodaj użytkownika aplikacji
 label.editAppUser   =   Edytuj użytkownika aplikacji
-label.userList      =   Lista użytkowników aplikacji
+label.userList      =   Lista użytkowników aplikacji
+
+error.field.required=   Pole jest wymagane
+error.email.invalid =   Błędny adres mailowy
+error.size.firstName=   Długość musi być pomiędzy {min} i {max}.
+# w starszej wersji biblioteki {2} i {1}