κ²μ¦μ ν΄λΌμ΄μΈνΈ μ¬μ΄λμ μλ² μ¬μ΄λ μμͺ½ λͺ¨λ ν΄μΌ νλ€.
νλ‘ νΈ μλμμ κ²μ¦νλ©΄ μ¬μ©μμκ² μλͺ»λ μ
λ ₯μ λν λΉ λ₯Έ νΌλλ°±μ μ€ μ μκ³ , λΆνμν μλ² λ¦¬μμ€ λλΉλ λΆνμν λ€νΈμν¬ λΉμ©μ μ€μΌ μ μλ€.
μλ² μ¬μ΄λμ μλͺ»λ λ°μ΄ν°κ° κ·Έλλ‘ λ©μΈ λ‘μ§μ νκ² λλ©΄ λΆμμ©μ΄ μ΄λ§μ΄λ§νκ³ λ°μ΄ν° syncκ° κΉ¨μ§λ©΄ 볡ꡬνκΈ°κΉμ§ κΈμ μ μν΄κ° λμ€κΈ° λλ¬Έμ λ°©μ΄ λ‘μ§μ λ§μ λ Έλ ₯μ΄ νμνλ€κ³ νμ ¨λ€. 무μ보λ€.. μΌκ·Όμ μ€μΌ μ μλ€κ³ νμ ¨λ€...ππ
νμμ μΆκ°ν λ 'μ΄λ¦'μ νμλ‘ μ λ ₯ λ°μμΌ νκ³ λλ¨Έμ§ μμλ μ λ ₯λ°μ§ μμλ λμνλ€.
Bean Validationμ μ¬μ©νκΈ° μν μμ‘΄κ΄κ³λ₯Ό μΆκ°νκΈ°
// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-validation'
// νμ μ
λ ₯ νΌ
public class MemberForm {
private Boolean check;
private Long id;
@NotBlank
private String memberName;
private String address;
private MultipartFile attachFile;
private String fileName;
public MemberForm() {}
}
@NotBlank : λΉκ° + κ³΅λ°±λ§ μλ κ²½μ°λ₯Ό νμ©νμ§ μλλ€.
<form action="item.html" th:action method="post" th:object="${member}" enctype="multipart/form-data">
<div>
<label for="memberName">μ΄λ¦</label>
<input type="text" id="memberName" th:field="*{memberName}"
th:errorclass="field-error" class="form-control" placeholder="μ΄λ¦μ μ
λ ₯νμΈμ">
<div class="field-error" th:errors="*{memberName}">μ΄λ¦ μ€λ₯</div>
</div>
...
</form>
// νμ μΆκ°
@GetMapping("/add")
public String addForm(Model model) {
model.addAttribute("member", new MemberForm());
return "addForm";
}
@PostMapping("/add")
public String saveMember(@Validated @ModelAttribute("member") MemberForm form, BindingResult bindingResult, RedirectAttributes redirectAttributes) throws IOException {
// κ²μ¦μ μ€ν¨νλ©΄ λ€μ μ
λ ₯ νΌμΌλ‘
if (bindingResult.hasErrors()) {
log.info("errors = {}", bindingResult);
return "addForm";
}
System.out.println(form);
Long savedId = memberService.save(form);
redirectAttributes.addAttribute("memberId", savedId);
redirectAttributes.addAttribute("status", true);
return "redirect:/basic/members/{memberId}";
}
@ModelAttribute κ°κ°μ νλ νμ λ³νμλ -> λ³νμ μ±κ³΅ν νλλ§ BeanValidation μ μ©
κ²μ¦ μ€λ₯κ° λ°μνλ©΄, FieldError , ObjectError λ₯Ό μμ±ν΄μ BindingResult μ λ΄μμ€λ€.
μ λ Έν μ΄μ μ΄λ¦μ κΈ°λ°μΌλ‘ λ©μμ§ μ½λλ₯Ό μμλλ‘ μμ±ν΄μ€λ€.
@NotBlank
NotBlank.member.memberName
NotBlank.memberName
NotBlank.java.lang.String
NotBlank
λ©μμ§λ‘ λ±λ‘νμ¬ μ¬μ©νκΈ°
//errors.properties
NotBlank.member.memberName=νμ μ΄λ¦μ μ
λ ₯ν΄μ£ΌμΈμ
NotBlank.memberName=μ΄λ¦μ μ
λ ₯ν΄μ£ΌμΈμ
NotBlank.java.lang.String=μ νν μ
λ ₯ν΄ μ£ΌμΈμ
NotBlank=μ
λ ₯ν΄μ£ΌμΈμ
νμ΄λ²λ€μ΄νΈ Validator κ΄λ ¨ λ§ν¬
곡μ μ¬μ΄νΈ: http://hibernate.org/validator/
곡μ λ©λ΄μΌ: https://docs.jboss.org/hibernate/validator/6.2/reference/en-US/html_single/ κ²μ¦ μ λ
Έν
μ΄μ
λͺ¨μ: https://docs.jboss.org/hibernate/validator/6.2/reference/en-US/html_single/#validator-defineconstraints-spec