똑같은 삽질은 2번 하지 말자

@Valid 와 BindingResult 본문

Spring/Spring Boot

@Valid 와 BindingResult

곽빵 2020. 4. 30. 11:16

@Valid

  • Dispatcherservlet이 메소드안에 선언된 객체를 만들어주고 값을 넣어준다.
  • @Valid선언된객체에 설정을 바탕으로 검사후 BindingResult에 담아준다.
  • 에러를 발생하려면 FieldError객체를 만들어서 BindingResult에 넣어준다.
  • 태그에서 object에 담긴 객체의 프로퍼티를 filed *{필드이름} 형식으로 사용한다
  • errors는 BindingResult에 있는 에러값을 출력해준다.
  • BindingResult.hasErrors : 에러가 있는지 검사한다.
  • thymeleaf를 사용하여 사용한 예제이다.
@Controller
public class MemberController {
	@Autowired
	private MemberService memberService;
	
	@GetMapping(value = "/members/new")
	public String createForm(Model model) {
		model.addAttribute("memberForm",new MemberForm());
		return "members/createMemberForm";
	}
	
	@PostMapping(value = "/members/new")
	public String create(@Valid MemberForm form, BindingResult result) {
		if(result.hasErrors()) {
			return "members/createMemberForm";
		}
		Address address = new Address(form.getCity(),form.getStreet(),form.getZipcode());
		Member member = new Member();
		
		member.setName(form.getName());
		member.setAddress(address);
		
		memberService.join(member);
		
		return "redirect:/";
	}
}
import org.hibernate.validator.constraints.NotEmpty;

public class MemberForm {
	@NotEmpty(message = "名前は必須です")
	private String name;
	private String city;
	private String street;
	private String zipcode;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header" />
<style>
.fieldError {
	border-color: #bd2130;
}
</style>
<body>
	<div class="container">
		<div th:replace="fragments/bodyHeader :: bodyHeader" />
		<form role="form" action="/members/new" th:object="${memberForm}"
			method="post">
			<div class="form-group">
				<label th:for="name">名前</label> <input type="text"
					th:field="*{name}" class="form-control" placeholder="お名前を入力して下さい"
					th:class="${#fields.hasErrors('name')}? 'form-control
fieldError' : 'form-control'">
				<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect
					date</p>
			</div>
			<div class="form-group">
				<label th:for="city">県</label> <input type="text"
					th:field="*{city}" class="form-control" placeholder="県を入力して下さい">
			</div>
			<div class="form-group">
				<label th:for="street">区</label> <input type="text"
					th:field="*{street}" class="form-control" placeholder="区を入力して下さい">
			</div>
			<div class="form-group">
				<label th:for="zipcode">郵便番号</label> <input type="text"
					th:field="*{zipcode}" class="form-control"
					placeholder="郵便番号を入力して下さい">
			</div>
			<button type="submit" class="btn btn-primary">Submit</button>
		</form>
		<br />
		<div th:replace="fragments/footer :: footer" />
	</div>
	<!-- /container -->
</body>
</html>
Comments