수업(국비지원)/Spring
[Spring] (MVC 2) 사용자 등록(join, User, UserController, ) - 유효성 검사
byeolsub
2023. 4. 21. 00:02
📌 join.jsp 생성
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- /springmvc1/src/main/webapp/WEB-INF/view/user/join.jsp --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>사용자 등록</title>
</head>
<body>
<h2>사용자 등록</h2>
<form:form modelAttribute="user" method="post" action="join">
<spring:hasBindErrors name="user">
<font color="red">
<c:forEach items="${errors.globalErrors}" var="error">
<spring:message code="${error.code}"/>
</c:forEach>
</font>
</spring:hasBindErrors>
<table board="1" style="board-collapse: collapse;">
<tr>
<td>아이디</td>
<td><form:input path="userid" onkeyup="idchk(rhis.value)"/>
<font color="red"><form:errors path="userid"/></font></td>
</tr>
<tr>
<td>비밀번호</td>
<td><form:password path="password" />
<font color="red"><form:errors path="password"/></font></td>
</tr>
<tr>
<td>이름</td>
<td><form:input path="username" />
<font color="red"><form:errors path="username"/></font></td>
</tr>
<tr>
<td>전화번호</td>
<td><form:input path="phoneno" />
<font color="red"><form:errors path="phoneno"/></font></td>
</tr>
<tr>
<td>우편번호</td>
<td><form:input path="postcode" />
<font color="red"><form:errors path="postcode"/></font></td>
</tr>
<tr>
<td>주소</td>
<td><form:input path="address" />
<font color="red"><form:errors path="address"/></font></td>
</tr>
<tr>
<td>이메일</td>
<td><form:input path="email" />
<font color="red"><form:errors path="email"/></font></td>
</tr>
<tr>
<td>생년월일</td>
<td><form:input path="birthday" />
<font color="red"><form:errors path="birthday"/></font></td>
</tr>
<tr><td colspan="2" align="center">
<input type="submit" value="등록">
<input type="reset" value="초기화"></td>
</tr>
</table>
</form:form>
</body>
</html>
📌 User.java 생성
package logic;
import java.util.Date;
public class User {
private String userid;
private String password;
private String username;
private String phoneno;
private String postcode;
private String address;
private String email;
private Date birthday;
//getter, setter, toString
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [userid=" + userid + ", password=" + password + ", username=" + username + ", phoneno=" + phoneno
+ ", postcode=" + postcode + ", address=" + address + ", email=" + email + ", birthday=" + birthday
+ "]";
}
}
📌 UserController.java 생성
package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import logic.ShopService;
import logic.User;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private ShopService service;
@GetMapping("*") // * : 그 외 모든 get 방식 요청
public ModelAndView join() {
ModelAndView mav = new ModelAndView();
mav.addObject(new User());
return mav;
}
}
- 사용자 등록 - 유효성 검사
📌 User.java 내용 추가
package logic;
import java.util.Date;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
public class User {
**@Size(min=3,max=10,message="아이디는 3자이상 10자 이하로 입력하세요.")**
private String userid;
**@Size(min=3, max=10, message="비밀번호는 3자 이상 10자 이하로 입력하세요.")**
private String password;
**@NotEmpty(message="사용자 이름은 필수 입니다.")**
private String username;
private String phoneno;
private String postcode;
private String address;
**@NotEmpty(message="이메일은 필수 입니다.")
@Email(message="email 형식으로 입력하세요.")**
private String email;
**@Past(message="생일은 과거 날짜만 가능합니다.")
@DateTimeFormat(pattern="yyyy-MM-dd")**
private Date birthday;
//getter, setter, toString
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [userid=" + userid + ", password=" + password + ", username=" + username + ", phoneno=" + phoneno
+ ", postcode=" + postcode + ", address=" + address + ", email=" + email + ", birthday=" + birthday
+ "]";
}
}
📌 UserController.java 생성
package controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import logic.ShopService;
import logic.User;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private ShopService service;
@GetMapping("*") // * : 그 외 모든 get 방식 요청
public ModelAndView getUser() {
ModelAndView mav = new ModelAndView();
mav.addObject(new User());
return mav;
}
**@PostMapping("join")
public ModelAndView join (@Valid User user, BindingResult bresult) {
ModelAndView mav = new ModelAndView();
if(bresult.hasErrors()) {
mav.getModel().putAll(bresult.getModel());
// bresult.reject("error.input.user");
return mav;
}
return mav;
}**
}
📌 spring-mvc.xml 내용 추가
<?xml version="1.0" encoding="UTF-8" ?>
<!-- /src/main/resources/spring-mvc.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- css,js,html 웹에서 제공되는 파일의 기본 기능 제외 -->
<mvc:default-servlet-handler />
<!-- controller,logic,dao 패키지를 먼저 scan해서 @Component 를 가진 클래스의 객체 생성 -->
<context:component-scan base-package="controller,logic,dao" />
<!-- web 환경에서 객체 주입을 위한 설정 : @Autowired,@Controller... 기능 사용 -->
<mvc:annotation-driven />
<!-- "viewResolver" 뷰결정자 : jsp 페이지의 위치 지정 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<!-- item/list : WEB-INF/view/item/list.jsp : 뷰 지정 -->
<property name="prefix"><value>/WEB-INF/view/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<!-- 파일 업로드 설정
요청시 enctype="multipart/form-data" 형식인 경우 작동.
p:maxUploadSize="104854600" : 100M 최대 업로드 가능한 크기 설정.
p:maxInMemorySize="10485460" : 10M까지는 메모리에 파일의 내용을 저장.
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxUploadSize="104854600" p:maxInMemorySize="10485460"></bean>
<!-- message 코드값을 저장한 properties 파일을 설정. : messages.properties
message 처리를 위한 설정 -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list><value>messages</value></list>
</property>
</bean>
<!-- 예외처리 -->
<bean id="exceptionHandler"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<value></value>
</property>
</bean>
</beans>
📌 messages.properties - 파일 만들기
## src/main/resources/messages.txt => src/main/resources/messages.properties \\uBCC0\\uACBD
error.login.password=\\uBE44\\uBC00\\uBC88\\uD638\\uB97C \\uD655\\uC778\\uD558\\uC138\\uC694.
error.input.user=\\uD68C\\uC6D0\\uAC00\\uC785 \\uC785\\uB825\\uD56D\\uBAA9\\uC744 \\uD655\\uC778\\uD558\\uC138\\uC694
error.input.login=\\uB85C\\uADF8\\uC778 \\uC785\\uB825\\uD56D\\uBAA9\\uC744 \\uD655\\uC778\\uD558\\uC138\\uC694
typeMismatch.birthday=\\uC0DD\\uB144\\uC6D4\\uC77C\\uC740 YYYY-MM-DD \\uD615\\uC2DD\\uC73C\\uB85C \\uC785\\uB825\\uD574 \\uC8FC\\uC138\\uC694
error.duplicate.user=\\uC911\\uBCF5\\uB41C \\uC544\\uC774\\uB514 \\uC785\\uB2C8\\uB2E4.
error.login.password=\\uBE44\\uBC00\\uBC88\\uD638 \\uC624\\uB958 \\uC785\\uB2C8\\uB2E4.
error.login.id=\\uC544\\uC774\\uB514\\uAC00 \\uC874\\uC7AC\\uD558\\uC9C0 \\uC54A\\uC2B5\\uB2C8\\uB2E4.
error.userid.search=\\uC544\\uC774\\uB514\\uB97C \\uCC3E\\uC744 \\uC218 \\uC5C6\\uC2B5\\uB2C8\\uB2E4.
error.password.search=\\uBE44\\uBC00\\uBC88\\uD638\\uB97C \\uCC3E\\uC744 \\uC218 \\uC5C6\\uC2B5\\uB2C8\\uB2E4.
error.required.userid=\\uC544\\uC774\\uB514\\uB97C \\uC785\\uB825\\uD558\\uC138\\uC694
error.required.email=EMAIL\\uC744 \\uC785\\uB825\\uD558\\uC138\\uC694
error.required.phoneno=\\uC804\\uD654\\uBC88\\uD638\\uB97C \\uC785\\uB825\\uD558\\uC138\\uC694