2020년 5월 15일 금요일

[Spring] Verifying Object Values with Bean Validation (JSR-303)

Enabling Bean Validation

pom.xml
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
 <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
 <version>5.2.1.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator-annotation-processor</artifactId>
    <version>5.2.1.Final</version>
</dependency>

servlet-context.xml
<beans:bean id="validator" 
            class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
Add a Validator bin to the servlet-context.xml.


Validation Annotation

 Use the following annunciations to check that the variable contains values that meet the conditions.

AnnotaionDescrption
@Size(min=m, max=n)Checks whether the string is m to n digits.
@NotNullCheck whether the variable value is null or not.
@NotBlankFor strings or arrays, check that they are not null and that they are not zero in length.
@Pattern("regrx")Examine whether the value of the variable meets the expression.
@EmailExamines variable values to satisfy email format.
@PastExamine if the time is in the past.
@FutureExamine if the time is in the future.
@AssertTrueChecks whether variable values are true.
@AssertFalseChecks whether variable values are false.

Using Validation annotations

  The Validation Annotation allows you to validate that the variable values meet these conditions.

MemberVO.java
public class UserVO {
 
    @Size(min=1, max=10)
    private String userId; // 1~10자리의 문자열
    private String password;
    private String passwordConfirm;
          ...
 Attach an annotation to the value of the field to which you want to apply the check. If you attach an annunciation as shown above, the variable must contain a string of 1 to 10 digits. Otherwise, it will cause an error.

member.jsp
<form:form modelAttribute="userVO" action="/test">
 <p>아이디</p>
 <form:input path="userId"/>
 <p>비밀번호</p>
 <form:input path="password"/>
 <p>비밀번호 확인</p>
 <form:input path="passwordConfirm"/>
 <input type="submit" />
</form:form>
Create a form tag to transfer values to userVO objects.

MemberController.java
@RequestMapping("/test")
    public String signUpSubmit(@ModelAttribute @Valid UserVO userVO, BindingResult result) {
  
        // 유효성 검사를 통과하지 못했을 때
        if (result.hasErrors()) {
            return "/signUp";
        
        // 유효성 검사를 통과했을 때
        } else {
            ...
            return "/main";
        }
        
    }
The value sent by @ModelAttribute will be contained in userVO. At this point, attach the @Vaild annoction to the object on which you want to run the validation and set the BindingResult result to the parameter. Then, if the validation fails, return to the page with the form tag and move on to the next page if it passes the validation.


Display error message on screen

 To display an error message on the screen, you need to do more work.

form:error Tag
<form:error path=userId cssClass="err"/>
 The form:error tag lets you float an error message for the userId variable. At this point, an error message is generated as a tag with the class attribute "err" so that the error message can be colored by css.

messages_ko_KR.properties
Size.userVO.userId = 아이디는 1~10자리이어야 합니다
Create /resources/messages/messages_ko_KR.properties file to create an error message. Error message said, "Annotation name.Object name.Variable name = Message.

servlet-context.xml
<!-- Register the Customer.properties -->
<beans:bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <beans:property name="basename" value="messages/messages" />
    <beans:property name="defaultEncoding" value="utf-8" />
</beans:bean>
 Register the messageSource bin in servlet-context.xml to use the contents of messages_ko_KR.properties as messages. When you finish all of this and run validation, the message you set at the time of the error will appear on the screen.

댓글 없음:

댓글 쓰기