6일차

|
// MVC 실습2




1. RegistrationController.java

package com.spring.mvc.ex02;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.mvc.ex02.component.MemberRegistRequest;
import com.spring.mvc.ex02.component.MemberRegistValidator;

@Controller("registrationController2")
@RequestMapping("/member/regist2")
public class RegistrationController {
 private static final String MEMBER_REGISTRATION_FORM = "member/registrationForm2";
 @Autowired
 private MemberService memberService2;

 @RequestMapping(method = RequestMethod.GET)
 public String form(@ModelAttribute("memberInfo") MemberRegistRequest memRegReq) {
  return MEMBER_REGISTRATION_FORM;
 }

 @RequestMapping(method = RequestMethod.POST)
 public String regist(
   @ModelAttribute("memberInfo") MemberRegistRequest memRegReq,
   BindingResult bindingResult) {
  new MemberRegistValidator().validate(memRegReq, bindingResult);
  if (bindingResult.hasErrors()) {
   return MEMBER_REGISTRATION_FORM;
  }
  memberService2.registNewMember(memRegReq);
  return "member/registered";
 }

 public void setMemberService(MemberService memberService) {
  this.memberService2 = memberService;
 }
}

2. MemberRegistValidator.java

package com.spring.mvc.ex02.component;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class MemberRegistValidator implements Validator {
	
	@Override
	public boolean supports(Class<?> clazz) {
		return MemberRegistRequest.class.isAssignableFrom(clazz); //검증할 수 있는 객체인지 리턴
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		MemberRegistRequest regReq = (MemberRegistRequest) target;
		if(regReq.getEmail() == null || regReq.getEmail().trim().isEmpty())
			errors.rejectValue("email", "required");
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "required");
		if(regReq.hasPassword()) {
			if(regReq.getPassword().length() < 5 )
				errors.rejectValue("password", "shortPassword");
			else if(!regReq.isSamePasswordConfirmPassword())
				errors.rejectValue("confirmPassword", "notSame");
		}
		Address address = regReq.getAddress();
		if(address == null) {
			errors.rejectValue("address", "required");
		} else {
			errors.pushNestedPath("address");
			try {
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address1", "required");
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address2", "required");
			} finally {
				errors.popNestedPath();
			}
		}
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday", "required");
	}

}

3. registrationForm2.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>회원 가입</title>
</head>
<body>

<spring:hasBindErrors name="memberInfo" />
<form method="post">
<label for="email">이메일</label>: 
<input type="text" name="email" id="email" value="${memberInfo.email}"/>
<form:errors path="memberInfo.email"/> <br/>

<label for="name">이름</label>: 
<input type="text" name="name" id="name" value="${memberInfo.name}" />
<form:errors path="memberInfo.name"/> <br/>

<label for="password">암호</label>: 
<input type="password" name="password" id="password" value="${memberInfo.password}"/>
<form:errors path="memberInfo.password"/> <br/>

<label for="password">확인</label>: 
<input type="password" name="confirmPassword" id="confirmPassword" value="${memberInfo.confirmPassword}"/>
<form:errors path="memberInfo.confirmPassword"/> <br/>

<label>주소</label>:
주소1 
<input type="text" name="address.address1" value="${memberInfo.address.address1}" />
<form:errors path="memberInfo.address.address1"/> <br/>
주소2
<input type="text" name="address.address2" value="${memberInfo.address.address2}" />
<form:errors path="memberInfo.address.address2"/> <br/>
우편번호
<input type="text" name="address.zipcode" value="${memberInfo.address.zipcode}" />
<form:errors path="memberInfo.address.zipcode"/> <br/>

<label>
 <input type="checkbox" name="allowNoti" value="true" ${memberInfo.allowNoti ? 'checked' : '' }/>
 이메일을 수신합니다.
</label>
<br/>
<label for="birthday">생일</label>: 형식: YYYYMMDD, 예: 20140101
<input type="text" name="birthday" id="birthday" value='<fmt:formatDate value="${memberInfo.birthday}" pattern="yyyyMMdd" />'/>
<form:errors path="memberInfo.birthday"/> <br/>

<input type="submit" value="가입" />

</form>
</body>
</html>

4. error.properties

required = 필수 항목입니다.
required.email = 이메일을 입력하세요.
minlength = 최소{1} 글자 이상 입력해야 합니다.
maxlength = 최대 {1} 글자 까지만 입력해야 합니다.
invalidIdOrPassword.loginCommand=아이디와 암호가 일치하지 않습니다.
invalidPassword=암호가 일치하지 않습니다.
shortPassword=암호 길이가 짧습니다.
notSame.confirmPassword=입력한 값이 암호와 같지 않습니다.
typeMismatch.birthday=날짜 형식이 올바르지 않습니다.

NotEmpty=필수 항목입니다.
NotEmpty.currentPassword=현재 암호를 입력하세요.
Email=올바른 이메일 주소를 입력해야 합니다.

badBeginDate=이벤트 시작일이 잘못되었습니다.
badEndDate=이벤트 종료일이 잘못되었습니다.
typeMismatch.beginDate=시작 날짜 형식이 올바르지 않습니다.
typeMismatch.endDate=종료 날짜 형식이 올바르지 않습니다.

5. dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
	xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />
	<context:component-scan base-package="com" />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<beans:property name="basenames">
			<beans:list>
				<beans:value>message.error</beans:value>
			</beans:list>
		</beans:property>
		<beans:property name="defaultEncoding" value="UTF-8" />
	</beans:bean>

</beans:beans>

// MVC실습 3

1. LoginController.java

package com.spring.mvc.ex03;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.mvc.ex03.component.Auth;
import com.spring.mvc.ex03.component.AuthenticationException;
import com.spring.mvc.ex03.component.Authenticator;
import com.spring.mvc.ex03.component.LoginCommand;
import com.spring.mvc.ex03.component.LoginCommandValidator;

@Controller
@RequestMapping("/auth/login")
public class LoginController {

 private static final String LOGIN_FORM = "auth/loginForm";
 @Autowired
 private Authenticator authenticator;

 @RequestMapping(method = RequestMethod.GET)
 public String loginForm(LoginCommand loginCommand) {
  return LOGIN_FORM;
 }

 @RequestMapping(method = RequestMethod.POST)
 public String login(@Valid LoginCommand loginCommand, Errors errors,
   HttpServletRequest request) {
  if (errors.hasErrors()) {
   return LOGIN_FORM;
  }
  try {
   Auth auth = authenticator.authenticate(loginCommand.getEmail(), loginCommand.getPassword());
   HttpSession session = request.getSession();
   session.setAttribute("auth", auth);
   return "redirect:/index.jsp";
  } catch (AuthenticationException ex) {
   // 화면에서 입력한 정보와 일치하는 것이 앖으면
   errors.reject("invalidIdOrPassword");
   return LOGIN_FORM;
  }
 }

 @InitBinder
 protected void initBinder(WebDataBinder binder) {
  binder.setValidator(new LoginCommandValidator());
 }

 public void setAuthenticator(Authenticator authenticator) {
  this.authenticator = authenticator;
 }
}

2. LoginCommandValidator.java

package com.spring.mvc.ex03.component;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class LoginCommandValidator implements Validator {
	
	@Override
	 public boolean supports(Class<?> clazz) {
	  return LoginCommand.class.isAssignableFrom(clazz);
	 }

	 @Override
	 public void validate(Object target, Errors errors) {
	  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required");
	  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required");
	 }
	}

'Bitcamp > BITCAMP - Spring FW' 카테고리의 다른 글

8일차  (0) 2019.10.17
7일차  (0) 2019.10.15
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
3일차  (0) 2019.10.07
And