2018년 5월 9일 수요일

스프링에서 검증 @Valid 와 BindingResult

@Valid

  • Dispatcherservlet이 메소드안에 선언된 객체를 만들어주고 값을 넣어준다.
  • @Valid선언된객체에 설정을 바탕으로 검사후 BindingResult에 담아준다.
  • 에러를 발생하려면 FieldError객체를 만들어서 BindingResult에 넣어준다.
  • 태그에서 object에 담긴 객체의 프로퍼티를 filed *{필드이름} 형식으로 사용한다
  • errors는 BindingResult에 있는 에러값을 출력해준다.
  • BindingResult.hasErrors : 에러가 있는지 검사한다.
  • lombok, thymeleaf를 사용하여 사용한 예제이다.
@Setter
@Getter
@ToString
public class UserJoinForm {

    @NotNull
    @Size(min = 2, max = 10)
    private String name;
    @NotNull
    @Size(min = 2, max = 50)
    private String email;
    @NotNull
    @Size(min = 2, max = 100)
    private String address;
    @NotNull
    @Size(min = 11, max = 11)
    private String phone;
    @NotNull
    @Size(min = 2, max = 15)
    private String password;
    @NotNull
    @Size(min = 2, max = 15)
    private String rePassword;
}
@PostMapping(path = "/join")
public String join(@Valid UserJoinForm userJoinForm, BindingResult bindingResult){
    //에러발생
    if(bindingResult.hasErrors()){
        return "/login/join";
    }
   
    if(!userJoinForm.getPassword().equals(userJoinForm.getRePassword())){
        FieldError fieldError = new FieldError("userJoinForm", "rePassword", "암호가 일치하지 않습니다");
        bindingResult.addError(fieldError);
        return "login/join";
    }

    User userByEmail = userService.getUserByEmail(userJoinForm.getEmail());
    if(userByEmail != null){
        FieldError fieldError = new FieldError("userJoinForm", "email", "이미 존재하는 email입니다.");
        bindingResult.addError(fieldError);
        return "login/join";
    }

    User user = new User();
    BeanUtils.copyProperties(userJoinForm, user);

    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    user.setPassword(passwordEncoder.encode(user.getPassword()));

    UserRole userRole = new UserRole();
    userRole.setRoleName("USER");
    user.addUserRole(userRole);

    User saveUser = userService.addUser(user);

    return;
}
<form class="form" id="formJoin" role="form" autocomplete="off"  novalidate="" method="POST" th:object="${userJoinForm}" th:action="@{/users/join}" action="#">
    <div class="form-group">
        <label for="name">name</label>
        <input type="text" class="form-control form-control-lg rounded-0" name="name" id="name" required="" th:field="*{name}">
        <small class="text-danger" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></small>
    </div>
    <div class="form-group">
        <label for="email">email</label>
        <input type="text" class="form-control form-control-lg rounded-0" name="email" id="email" required="" th:field="*{email}">
        <small class="text-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></small>
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control form-control-lg rounded-0" id="password" name="password" required="" th:field="*{password}" >
        <small class="text-danger" th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></small>
    </div>
    <div class="form-group">
        <label>Re Password</label>
        <input type="password" class="form-control form-control-lg rounded-0" id="rePassword" required="" th:field="*{rePassword}" >
        <small class="text-danger" th:if="${#fields.hasErrors('rePassword')}" th:errors="*{rePassword}"></small>
    </div>
    <div class="form-group">
        <label>phone</label>
        <input type="text" class="form-control form-control-lg rounded-0" id="phone" name="phone" required="" size="11" maxlength="11" th:field="*{phone}">
        <small class="text-danger" th:if="${#fields.hasErrors('phone')}" th:errors="*{phone}"></small>
    </div>
    <div class="form-group">
        <label>address</label>
        <button type="button" class="btn btn-info btn-sm" id="addressSearch">search</button>
        <input type="text" class="form-control form-control-lg rounded-0" id="address" name="address" required="" th:field="*{address}">
        <small class="text-danger" th:if="${#fields.hasErrors('address')}" th:errors="*{address}"></small>
    </div>
    <div>
        <label class="custom-control custom-checkbox">
            <input type="checkbox" class="">
            <span class="custom-control-indicator"></span>
            <span class="custom-control-description small text-dark">Remember me on this computer</span>
        </label>
    </div>
    <i class="fab fa-facebook"></i>
    <div class="form-group row">
        <div class="col-sm-10">
            <a th:href="@{/sign-in/facebook}">facebook 가입 및 로그인</a>
        </div>
    </div>
    <button type="submit" class="btn btn-success btn-lg float-right" id="join">Join</button>
</form>
Share:

0 개의 댓글:

댓글 쓰기