hanker
Spring boot - HTML 입력값 검사 ( Valid example ) 본문
1. TestVO 작성
@Data
public class TestVO implements Serializable {
private static final long serialVersionUID = 9203343211087202441L;
@NotEmpty(message = "반드시 값이 존재하고 길이 혹은 크기가 0보다 커야합니다.")
@Size(max = 100)
private String test;
}
2. TestController 작성
@Controller
@RequestMapping("/test")
public class TestController {
@GetMapping
public String testView(TestVO testVO){
return "test/testInput";
}
@PostMapping
public String test(@Valid TestVO testVO, BindingResult result,
Model model, @RequestParam("test") String test){
if(result.hasErrors()){
return "test/testInput";
}
model.addAttribute("rs", test);
return "test/testOutput";
}
}
3. testInput.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>HTML 입력값 검사 Example</h2>
<form th:action="@{test}" th:Object="${testVO}" method="post">
<div>
<input type="text" th:field="*{test}" th:class="${#fields.hasErrors('test')} ? 'error'"/>
<span th:if="${#fields.hasErrors('test')}" th:errors="*{test}"></span>
</div>
<div>
<input type="submit" />
</div>
</form>
</body>
</html>
* 아무것도 입력하지 않았을 때
* 100글자 이상
* 알맞게 넣었을 때
testOutput.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>입력 결과 확인</h2>
<div>입력하신 결과는 [ <span th:text="${rs}"></span> ] 입니다.</div>
</body>
</html>
'SPRING' 카테고리의 다른 글
Spring JPA - referencedColumnName (feat. @JoinColumn) (0) | 2021.05.27 |
---|---|
Spring - Security Static 경로 인증 무시(403 Error) (0) | 2021.05.09 |
Spring - Thymeleaf 경로 설정 (templates) (0) | 2021.04.27 |
Spring boot - Log 사용 (0) | 2021.04.26 |
Spring - local image 가져오기 (0) | 2021.04.20 |