'spring @email'에 해당되는 글 1건

 

1. Spring Validataion Annotation 종류

    # hibernate 공식 문서 :  http://hibernate.org/validator/

    # hibernate annotation 종류 : https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-builtin-constraints

 

The Bean Validation reference implementation. - Hibernate Validator

Express validation rules in a standardized way using annotation-based constraints and benefit from transparent integration with a wide variety of frameworks.

hibernate.org

2. pom.xml에 hibernate 의존성 추가

 <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.8.Final</version>
        </dependency>

3. VO 생성하기

package VO;

import javax.validation.constraints.*;

public class JoinVO {

    // 길이 지정
    @Size(min = 5 , max = 20 , message = "5 - 20 사이에 글자")
    private String id;

    // 길이 지정
    @Size(min = 5 , max = 20 , message = "5 - 20 사이에 글자")
    private String pw;

    // 0 - 99 구간 , 소수점 허용 안함
    @Digits(integer = 2, fraction = 0)
    @Min(0)
    @Max(99)
    private int age;

    // 이메일 형식 체크
    @Email(message = "이메일 형식에 맞게 넣으세요")
    private String email;

    private String information;

    private String hobby;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPw() {
        return pw;
    }

    public void setPw(String pw) {
        this.pw = pw;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getInformation() {
        return information;
    }

    public void setInformation(String information) {
        this.information = information;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "JoinVO{" +
                "id='" + id + '\'' +
                ", pw='" + pw + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", information='" + information + '\'' +
                ", hobby='" + hobby + '\'' +
                '}';
    }
}

4. controller - ValidController.java

package Controller;

import VO.JoinVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.List;

@Controller
public class ValidController {

    /**
     * joinForm 불러오기
     * @param joinVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/JoinForm", method = RequestMethod.GET)
    public String boardRegisterForm(@ModelAttribute("joinVO") JoinVO joinVO, Model model) throws Exception {
        return "JoinForm";
    }

    /**
     * joinForm 내용 검증
     * @param joinVO
     * @param bindingResult
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/joinInsert", method = RequestMethod.POST)
    public String boardInsert(@Valid JoinVO joinVO, BindingResult bindingResult, Model model) throws Exception {
        // Form 정보 출력
        System.out.println(joinVO.toString());
        // Validation 결과의 에러의 목록 출력
        if(bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            for(ObjectError error : errors){
                System.out.println(error.getDefaultMessage());
            }
            return "JoinForm";
        }

        return "redirect:/JoinForm";
    }
}

5. JSP 페이지 - JoinForm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--JSTL 문법 --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%--form:form 태그 사용--%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>가입하세요</title>
</head>
<body>
<h1>회원가입</h1>
<form:form modelAttribute="joinVO" action="/joinInsert" method="post">
<%--    <form:errors path="*" cssClass="error"/>--%>
    <table border="1">
        <tbody>
        <tr>
            <th>이름</th>
            <td>
                <form:input path="id" id="id" size="20" maxlength="20"/>
                <form:errors path="id" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>비밀번호</th>
            <td>
                <form:password path="pw" id="pw" size="20" maxlength="20"/>
                <form:errors path="pw" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>나이</th>
            <td>
                <form:input path="age" id="age" size="20" maxlength="20"/>
                <form:errors path="age" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>이메일</th>
            <td>
                <form:input path="email" id="email" size="20" maxlength="20"/>
                <form:errors path="email" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>내용</th>
            <td>
                <form:textarea path="information" id="content"/>
                <form:errors path="information" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <td>취미</td>
            <td><form:select path="hobby">
                <form:option value="soccer" label="축구" />
                <form:option value="basketball" label="농구" />
                <form:option value="tennis" label="테니스" />
            </form:select></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="등록"/></td>
        </tr>
        </tbody>
    </table>
</form:form>
</body>
</html>

6.결과화면 

   - 등록을 눌렀을 때, 타당하지 않은 이유를 표시함

블로그 이미지

미나미나미

,