Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 개발순서
- vector미분
- 1차예선
- Fisher discriminant analysis
- CH01
- 스터디
- bisection
- Numerical optimization
- Perceptron Convergence theorem
- directed graphical model
- 알고리즘
- 자바ORM표준JPA프로그래밍
- 알고리즘대회
- 인공지능
- chapter01
- chapter02
- 5397번
- MySQL
- falsePosition
- 선형판별분석
- undirected graphical model
- 델타 rule
- 선형분류
- 2018
- SCPC
- 로지스틱 회귀
- 이것이 MySQL이다
- graphical models
- 근구하기
- secant
Archives
- Today
- Total
computer_study
[Spring] 12. MVC2 : 메시지, 커맨드 객체 검증 본문
1. 프로젝트 준비
2. <spring:message>태그로 메시지 출력하기
- 문자열을 별도 파일에 작성하고, JSP 코드에서 사용하기 위한 방법
- 작업 순서
- 문자열을 담은 메시지 파일 작성
member.register=회원가입
term=약관
term.agree=약관동의
next.btn=다음단계
member.info= 회원정보
email=이메일
- 메시지 파일에서 값을 읽어오는 MessageSource빈을 설정
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer{
@Bean
public MessageSource messageSource(){// 빈의 아이디를 mesageSource로 지정해야 한다.
ResourceBundleMessageSource ms =
new ResourceBundleMessageSource();
ms.setBasenames("message.label");// message패키지에 속한 label프로퍼티 파일로 부터 읽어오겠다.
// ms.setBasenames("message.label", "message.error") 처럼 여러 개도 가능.
ms.setDefaultEncoding("UTF-8");
return ms;
}
}
- JSP코드에서 <spring:message>태그를 사용해서 메시지 출력
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
...
<head>
<title><spring:message code="memeber.register"/></title>
</head>
<body>
<h2><spring:message code ="term"/></h2>
...
메시지 처리를 위한 MessageSource와 <spring:message>태그
스프링은 지역에 상관없이 메시지를 관리할 수 있도록 MessageSource인터페이스를 정의하고있다.
(MessageSource의 getMessage()메서드를 이용해서 필요한 메시지를 가져와 사용하는 식)
public interface MessageSource{
String getMessage(String code, Object[]args. Locale locale)
throws NoSuchMesageException;
// 같은 코드라도 지역에 따라 다른 메시지를 제공할 수 있도록 하기 위해
}
<spring:message> 태그의 메시지 인자 처리
# label.properties 파일
register.done=<strong>{0}님 ({1})</strong>, 회원 가입을 완료했습니다
<!-- 방법1 -->
<spring:message code="registoer.done"
arguments="${registerRequest.name},$registerRequest.email}"/>
<!-- 방법 2 -->
<spring:message code="registoer.done">
<spring:argument value="${registerRequest.name}"/>
<spring:argument value="${registerRequest.email}"/>
</spring:message>
3. 커맨드 객체의 값 검증과 에러 메시지 처리
커맨드 객체 검증과 에러 코드 지정
validator, Errors 인터페이스 사용
- validate()함수 작성
- 객체를 검증하고 오류 결과를 Errors에 담는 기능을 정의
- 검사 대상 객체의 특정 프로퍼티나 상태가 올바른지 검사
- 올바르지 않다면 Errors의 rejectValue() 메서드를 이용해서 에러 코드 저장
- errors.rejectValue("email", "required")
- Errors와 ValidationUtils클래스의 주요 메서드
- Errors
- reject(String errorCode)
- reject(String errorCode, String defaultMessage)
- reject(String errorCode, Object[] errorArgs, String defaultMessage)
- rejectValue(String field, String errorCode)
- rejectValue(String field, String errorCode, String defaultMesage)
- rejectValue(String field, String errorCode, Object[] errorArgs, String default Message)
- ValidationUtils
- rejectIfEmpty(Errors errors, String field, String errorCode)
- rejectIfEmpty(Errors errors, String field, String errorCode, Object[] errorArgs)
- rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode)
- rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode, Object[] errorArgs)
- Errors
JSP에서 에러 코드로부터 메시지 출력
<form:errors>태그를 사용하면 에러에 해당하는 메시지를 출력할 수 있다.
<html>
<head>
</head>
<body>
<p>
<label><spring:message code="email" />:<br>
<form:input path="email" />
<form:errors path="email" />
</p>
</bodt>
</html>
- 해당 메시지 코드를 찾을 때 규칙
- 에러코드 + "." + 커맨드객체이름 + "." + 필드명
- 에러코드 + "." + 필드명
- 에러코드 + "." + 필드타입
- 에러코드
- 프로퍼티 타입이 List나 목록인 경우
- 에러코드 + "." + 커맨드객체이름 + "." + 필드명[인덱스].중첩필드명
- 에러코드 + "." + 커맨드객체이름 + "." + 필드명.중첩필드명
- 에러코드 + "." + 필드명[인덱스].중첩필드명
- 에러코드 + "." + 필드명.중첩필드명
- 에러코드 + "." + 중첩필드명
- 에러코드 + "." + 필드타입
- 에러코드
- ex
- errors.rejectValue("email", "required")코드로 required에러코드를 추가한 상태고, 커맨드 객체의 이름이 registerRequest라면
- required.registerRequest.email
- required.email
- required.String
- required
- 순서로 메시지 코드를 검색한다.
# label.properties 파일
required=필수항목입니다.
4. 글로벌 범위 Validator와 컨트롤러 범위 Validator
글로벌 범위 Validator 설정과 @Valid 애노테이션
- 글로벌 범위 Validator
- 모든 컨트롤러에 적용할 수 있는 validator
- 적용 위한 설정
- 설정 클래스에서 WebMvcConfigurer의 getValidator()메서드가 Validator 구현 객체를 리턴하도록 구현
- 글로벌 범위 Validator가 검증할 커맨드 객체에 @Valid 애노테이션 적용
- Error타입 파라미터가 없다면 검증 실패 시 400 에러를 응답한다.
// WebMvcConfigurer 인터페이스
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public Validator getValidator(){
return new RegisterRequestValidator();
}
}
// @Valid 애노테이션 사용
// 글로벌 범위 Validator가 해당 타입을 검증할 수 있는지 확인한다.
import javax.validation.Valid;
@Controller
public class RegisterController{
@PostMapping("/register/step3")
public String handleStep3(@Valid RegisterRequest reReq, Errors errors){
...
}
}
@InitBinder 애노테이션을 이용한 컨트롤러 범위 Validator
@Controller
public clas RegisterController{
...
@InitBinder
protected void initBinder(WebDataBinder binder){
binder.setValidator(new RegisterRequestValidator());
}
}
어떤 validator가 커맨드 객체를 검증할 지 initBinder()메서드가 결정한다.
위 예시에선 RegisterRequestValidator()를 @Valid애노테이션이 붙은 객체를 검증할 때 사용.
5. Bean Validation을 이용한 값 검증 처리
Validator작성 없이 애노테이션만으로 커맨드 객체의 값 검증을 처리할 수 있다.
초기 오류메시지는 Bean Validation 프로바이더가 기본으로 제공한다.
- 애노테이션이름.커맨드객체모델명.프로퍼티명
- 애노테이션이름.프로퍼티명
- 애노테이션이름
위 규칙을 따르는 메시지 코드를 메시지 프로퍼티 파일에 추가하여 메시지를 바꿀 수 있다.
Bean Validation 주요 애노테이션
p.350, p.351 표 참고
- 필수 입력 값을 검사할 때에는 @NotNull과 @Size를 함께 사용해야 한다.
'스터디 > 스프링5 프로그래밍 입문' 카테고리의 다른 글
[Spring] 14. MVC4 : 날짜 값 변환, @PathVariable, 익셉션 처리 (0) | 2022.05.23 |
---|---|
[Spring] 13. MVC3 : 세션, 인터셉터, 쿠키 (0) | 2022.05.16 |
[Spring] 11. MVC1 : 요청 매핑, 커맨드 객체, 리다이렉트, 폼 태그, 모델 (0) | 2022.05.09 |
[Spring] 10. 스프링 MVC 프레임워크 동작 방식 (0) | 2022.05.06 |
[Spring] 09. 스프링 MVC 시작하기 (0) | 2022.04.27 |
Comments