스프링 MVC 2 : 메시지, 커맨드 객체 검증
<spring:message> 태그로 메시지 출력하기
1. 해당 위치에 문자열을 담은 메시지파일을 작성
member.register=회원가입
term=약관
term.agree=약관동의
next.btn=다음단계
member.info=회원정보
email=이메일
name=이름
password=비밀번호
password.confirm=비밀번호 확인
register.btn=가입 완료
register.done=<strong>{0}님 </strong>, 회원 가입을 완료했습니다.
go.main=메인으로 이동
required=필수항목입니다.
bad.email=이메일이 올바르지 않습니다.
duplicate.email=중복된 이메일입니다.
글씨가 깨져서 나온다면
Properties에서 밑에 이미지 처럼 UTF-8 설정
2. 메시지 파일에서 값을 읽어오는 MessageSource 빈을 설정
package config;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/main").setViewName("main");
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasenames("message.label");
ms.setDefaultEncoding("UTF-8");
return ms;
}
}
3. JSP 코드에서 <spring:message> 태그를 사용해서 메시지를 출력한다.
taglib 임포트 / <spring:message code="사용 할 문자열" /> 사용법
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<title><spring:message code="member.register" /></title>
</head>
<body>
<h2><spring:message code="term" /></h2>
<p>약관 내용</p>
<form action="step2" method="post">
<label>
<input type="checkbox" name="agree" value="true">
<spring:message code="term.agree" />
</label>
<input type="submit" value="<spring:message code="next.btn" />" />
</form>
</body>
</html>
<spring:message> 태그의 메시지 인자 처리
@PostMapping("/register/step2")
public String handleStep2(
@RequestParam(value = "agree", defaultValue = "false") Boolean agree,
Model model) {
if (!agree) {
return "register/step1";
}
model.addAttribute("registerRequest", new RegisterRequest());
return "register/step2";
}
arguments 속성을 사용해서 register.done 메시지의 {0}dnlcldp 삽입할 값을 설정
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<title><spring:message code="member.register" /></title>
</head>
<body>
<p><spring:message code="register.done"
arguments="${registerRequest.name}" />
</p>
<p><a href="<c:url value='/main'/>">[<spring:message code="go.main" />]</a></p>
</body>
</html>
커맨드 객체의 값 검증과 에러 메시지 처리
1. 커맨드 객체를 검증하고 결과를 에러 코드로 저장
스프링 프레임워크에서 지원되는 Validator 인터페이스 구현
package spring;
public class RegisterRequest {
private String email;
private String password;
private String confirmPassword;
private String name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isPasswordEqualToConfirmPassword() {
return password.equals(confirmPassword);
}
}
supports 메서드에는 위에 코드처럼 대상이 되는 커맨드 객체 지정
package controller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import spring.RegisterRequest;
public class RegisterRequestValidator implements Validator {
private static final String emailRegExp =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" +
"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private Pattern pattern;
public RegisterRequestValidator() {
pattern = Pattern.compile(emailRegExp);
}
@Override
public boolean supports(Class<?> clazz) {
// 대상이 되는 커맨드 객체
return RegisterRequest.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
RegisterRequest regReq = (RegisterRequest) target;
// 이메일 프로퍼티 값 유효하지 확인
if(regReq.getEmail() == null || regReq.getEmail().trim().isEmpty()) {
errors.rejectValue("email", "required");// 에러 코드 추가
}else {// 정규표현시을 이용해서 이메일이 올바른지 확인
Matcher matcher = pattern.matcher(regReq.getEmail());
if(!matcher.matches()) {
errors.rejectValue("email", "bad");// 에러 코드 추가
}
}
// ValidationUtils 클래스 활용
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required");
ValidationUtils.rejectIfEmpty(errors, "password", "required");
ValidationUtils.rejectIfEmpty(errors, "confirmPassword", "required");
if(!regReq.getPassword().isEmpty()) {
if(!regReq.isPasswordEqualToConfirmPassword()) {
errors.rejectValue("confirmPassword", "nomatch");
}
}
}
}
그리고 구현한 validate() 메서드는 두 개의 파라미터를 갖게 되는데 target 파라미터는 검사 대상 객체이고
errors 파라미터는 검사 결과 에러 코드를 설정하기 위한 객체이다. 순서는
1. 검사 대상 객체의 특정 프로퍼티나 상태가 올바른지 검사
2. 올바르지 않다면 Errors의 rejectValue() 메서드를 이용해서 에러 코드 저장한다.
2. 컨트롤러 설정
커맨드 객체 파라미터 뒤에 Errors 타입 파라미터가 위치하면, 스프링 MVC는 해당 메서드를 호출할 때 커맨드 객체와
연결된 Errors 객체를 생성해서 파라미터로 전달한다.
@PostMapping("/register/step3")
public String handleStep3(RegisterRequest regReq, Errors errors) {
new RegisterRequestValidator().validate(regReq, errors);
if(errors.hasErrors()) {
return "register/step2";
}
try {
memberRegisterService.regist(regReq);
return "register/step3";
} catch (DuplicateMemberException ex) {
return "register/step2";
}
}
3. 커맨드 객체의 에러 메시지 출력하기
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<title><spring:message code="member.register" /></title>
</head>
<body>
<h2><spring:message code="member.info" /></h2>
<form:form action="step3" modelAttribute="registerRequest">
<p>
<label><spring:message code="email" />:<br>
<form:input path="email" />
<form:errors path="email" />
</label>
</p>
<p>
<label><spring:message code="name" />:<br>
<form:input path="name" />
</label>
</p>
<p>
<label><spring:message code="password" />:<br>
<form:password path="password" />
</label>
</p>
<p>
<label><spring:message code="password.confirm" />:<br>
<form:password path="confirmPassword" />
</label>
</p>
<input type="submit" value="<spring:message code="register.btn" />">
</form:form>
<%--
<form action="step3" method="post">
<p>
<label>이메일:<br>
<input type="text" name="email" id="email" value="${registerRequest.email}">
</label>
</p>
<p>
<label>이름:<br>
<input type="text" name="name" id="name" value="${registerRequest.name}">
</label>
</p>
<p>
<label>비밀번호:<br>
<input type="password" name="password" id="password">
</label>
</p>
<p>
<label>비밀번호 확인:<br>
<input type="password" name="confirmPassword" id="confirmPassword">
</label>
</p>
<input type="submit" value="가입 완료">
</form>
--%>
</body>
</html>
'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글
2023-08-29 71일차 (0) | 2023.08.30 |
---|---|
2023-08-25 69일차 (0) | 2023.08.25 |
2023-08-23 67일차 (0) | 2023.08.23 |
2023-08-22 66일차 (0) | 2023.08.23 |
2023-08-21 65일차 (0) | 2023.08.21 |