Maven이용 시 pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
Gradle이용 시 build.gradle
implementation 'org.springframework.boot:spring-boot-starter-validation'
controller
import com.godcoder.myhome.model.Board; import com.godcoder.myhome.repository.BoardRepository; import com.godcoder.myhome.validator.BoardValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.thymeleaf.util.StringUtils; import javax.persistence.EntityExistsException; import javax.validation.Valid; import java.util.List; @Controller @RequestMapping("/board") public class BoardController { @Autowired private BoardRepository boardRepository; @Autowired private BoardValidator boardValidator; @GetMapping("/form") public String form(Model model, @RequestParam(required = false) Long id, Board board){ if(id==null){ model.addAttribute("board", board); }else{ Board board2=boardRepository.findById(id).orElseThrow(EntityExistsException::new); model.addAttribute("board", board2); } return "board/form"; } @PostMapping("/form") public String boardSubmit(@Valid Board board, BindingResult bindingResult , Model model) { boardValidator.validate(board, bindingResult); if(bindingResult.hasErrors()){ return "board/form"; } boardRepository.save(board); model.addAttribute("board", board); return "redirect:/board/list"; } }
board
import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.lang.NonNull; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.Size; @Entity @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Board { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NonNull @Size(min=2, max=30, message = "제목은 2자 이상 30 이하여야 합니다.!!!") private String title; private String content; }
import com.godcoder.myhome.model.Board; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import org.thymeleaf.util.StringUtils; import javax.validation.ConstraintViolation; import javax.validation.executable.ExecutableValidator; import javax.validation.metadata.BeanDescriptor; import java.util.Set; @Component public class BoardValidator implements Validator { @Override public boolean supports(Class clazz) { return Board.class.equals(clazz); } @Override public void validate(Object obj, Errors e) { Board board= (Board) obj; if(StringUtils.isEmpty(board.getContent())){ e.rejectValue("content", "key", "내용을 입력해 주세요.11"); } } }
form.html
<main role="main" class="container"> <div class="starter-template"> <h1>게시판</h1> </div> <form action="#" th:action="@{/board/form}" th:object="${board}" method="post"> <input type="hidden" class="form-control" id="id" th:field="*{id}"> <div class="form-group"> <label for="title">제목</label> <input type="text" class="form-control" id="title" th:field="*{title}" th:classappend="${#fields.hasErrors('title')}? 'is-invalid' :''" > <div th:if="${#fields.hasErrors('title')}" th:errors="*{title}" class="invalid-feedback">title Error</div> </div> <div class="form-group"> <label for="content">내용</label> <textarea class="form-control" id="content" rows="3" th:field="*{content}" th:classappend="${#fields.hasErrors('content')}? 'is-invalid' :''" ></textarea> <div th:if="${#fields.hasErrors('content')}" th:errors="*{content}" class="invalid-feedback">content Error</div> </div> <div class="text-right"> <button type="submit" class="btn btn-primary" >확인</button> <a class="btn btn-primary" th:href="@{/board/list}" >취소</a> </div> </form> </main><!-- /.container -->
커스텀 Validation 는
Validator 상속 받는 도메인 객체 BoardValidator 클래스 생성 후 유효성 체크 코드를 작성후 다음과 같이 사용
@Autowired private BoardValidator boardValidator; @PostMapping("/form") public String boardSubmit(@Valid Board board, BindingResult bindingResult , Model model) { boardValidator.validate(board, bindingResult); if(bindingResult.hasErrors()){ return "board/form"; } boardRepository.save(board); model.addAttribute("board", board); return "redirect:/board/list"; }
참조
:
https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/validation.html
댓글 ( 4)
댓글 남기기