등록 수정 validation 구분

최주영·2024년 2월 27일
0

springboot

목록 보기
10/14
  • MemberDto클래스와 MemberSaveForm 클래스와 MemberUpdateForm 클래스 구분
  • 두개의 객체마다 각각 validation을 다르게 처리하기 위해서 구분
  • MemberSaveForm은 age컬럼에 validation이 적용되있지만, MemberUpdateForm에는 적용 x
// MemberDto
package com.joo.usedmarket1.dto;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class MemberDto {
	
	private String user_Id;
	private String password;
	private String username;
	private int age;
	private String email;
	private String phone;
	private String address;
	private String hobby;
	private Date enroll_Date;
}



// MemberSaveForm
package com.joo.usedmarket1.validation;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class MemberSaveForm {
	
	@NotEmpty(message = "아이디는 반드시 입력하세요!")
	@Size(min=4, message = "아이디는 최소 4글자 이상 입력하세요") // 최소 4글자
	private String user_Id;
	@Pattern(regexp  = "(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[~!@#$%^&*()])[a-zA-Z~!@#$%^&*()]{8,}"
			, message = "영소문자, 대문자, 특수기호를 포함하고 8글자 이상 작성")
	private String password;
	@NotEmpty
	private String username;
	@Min(value=15,message = "15살이상 입력")@Max(value = 150,message = "150이하 입력")
	private int age;
	@Email
	private String email;
	@NotEmpty
	private String phone;
	private String address;
	private String hobby;
}


// MemberUpdateForm
package com.joo.usedmarket1.validation;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class MemberUpdateForm {
	
	@NotEmpty(message = "아이디는 반드시 입력하세요!")
	@Size(min=4, message = "아이디는 최소 4글자 이상 입력하세요") // 최소 4글자
	private String user_Id;
	@Pattern(regexp = "(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[~!@#$%^&*()])[a-zA-Z~!@#$%^&*()]{8,}"
			, message = "영소문자, 대문자, 특수기호를 포함하고 8글자 이상 작성")
	private String password;
	@NotEmpty
	private String username;
	
	//수정시에는 나이 자유롭게 변경 가능
	private int age;
	
	@Email
	private String email;
	@NotEmpty
	private String phone;
	private String address;
	private String hobby;
}
  • member 컨트롤러
@Slf4j
@Controller
@RequestMapping("/member")
public class MemberController {

	private MemberService service;

	public MemberController(MemberService service) {
		this.service = service;
	}

	@GetMapping("/memberAll")
	public String selectMemberAll(Model m) {
		m.addAttribute("members", service.selectMemberAll());
		return "member/memberList";
	}
		
	
	 @GetMapping("/insertMember")  // 회원가입 페이지로 이동
	 public String intsertMemberView(@ModelAttribute("memberDto") MemberDto m) { 
		 // @ModelAttribute값은 회원가입페이지 insertMember.jsp view에서 <springform:form> 태그의 modelAttribute 값과 동일해야함
		 return "member/insertMember"; 
	 }
	 
	
	@PostMapping("/insertMember.do") 
    // insertMember.jsp 회원가입페이지에서 설정한 <springform:form> 태그의 modelAttribute 값과 동일
    // 회원가입폼으로 구분한 객체 넣기 -> MemberSaveForm saveForm
	public String insertMember(@Validated @ModelAttribute("memberDto") MemberSaveForm saveForm, BindingResult isResult, Model model){
		if(isResult.hasErrors()) {
			return "member/insertMember";
		}else {
			
			MemberDto member = new MemberDto();
			member.setUser_Id(saveForm.getUser_Id());
			member.setPassword(saveForm.getPassword());
			member.setUsername(saveForm.getUsername());
			member.setAge(saveForm.getAge());
			member.setEmail(saveForm.getEmail());
			member.setPhone(saveForm.getPhone());
			member.setAddress(saveForm.getAddress());
			member.setHobby(saveForm.getHobby());
			if(service.insertMember(member) >= 1) {
				System.out.println("성공");
			}else {
				System.out.println("실패");
			}	
			return "redirect:/";
		}
	}
	
	@GetMapping("edit/{user_Id}") // 쿼리스트링값으로 넘겨준 유저아이디 값을 받아서 해당 아이디의 객체 찾기
	public String editForm(@PathVariable String user_Id, Model model,@ModelAttribute("memberDto") MemberDto m) {
		MemberDto member = service.selectMemberById(user_Id);
		model.addAttribute("member",member);
		return "member/editForm";
	}
	
	@PostMapping("edit/{user_Id}") 
    // 위와동일하게  eidtForm.jsp에서 설정한 <springform:form> 태그의 modelAttribute 값과 동일
    // 회원수정폼으로 구분한 객체 넣기 -> MemberUpdateForm form
	public String edit(@PathVariable String user_Id, @Validated @ModelAttribute("memberDto") MemberUpdateForm form,BindingResult isResult) {
		
		if(isResult.hasErrors()) {
			log.info("errors={}",isResult);
			return "member/editForm";
		}
		
		System.out.println(form);
		
		MemberDto memberParam = new MemberDto();
		memberParam.setUser_Id(form.getUser_Id());
		memberParam.setPassword(form.getPassword());
		memberParam.setUsername(form.getUsername());
		memberParam.setAge(form.getAge());
		memberParam.setEmail(form.getEmail());
		memberParam.setPhone(form.getPhone());
		memberParam.setAddress(form.getAddress());
		memberParam.setHobby(form.getHobby());
		
		System.out.println(memberParam);
		
		if(service.update(memberParam)>=1) {
			System.out.println("성공");
		}else {
			System.out.println("실패");
		}

		return "redirect:/member/edit/{user_Id}";
	}
}
  • ServiceImpl
package com.joo.usedmarket1.service;


@Service
public class MemberServiceImpl implements MemberService{
	
	private MemberDao dao;
	private SqlSession session;
	public MemberServiceImpl(MemberDao dao, SqlSession session) {
		this.dao = dao;
		this.session = session;
	}
	
	@Override
	public List<MemberDto> selectMemberAll() {
		return dao.selectMemberAll(session);
	}

	@Override
	public int insertMember(MemberDto m) {
		return dao.insertMember(session, m);
	}

	@Override
	public MemberDto selectMemberById(String userId) {
		return dao.selectMemberById(userId); //session은 보낼필요없음(내부적으로처리됨)
	}


	@Override
	public int update(MemberDto memberParam) {
		return dao.update(session,memberParam);
	}
}
  • DaoImpl
package com.joo.usedmarket1.dao;


@Repository
public class MemberDaoImpl implements MemberDao {

	private MemberMapper mapper;
	 
	public MemberDaoImpl(MemberMapper mapper) { // mybatis가 mapper기준으로 처리
		this.mapper = mapper;
	}
	
	@Override
	public List<MemberDto> selectMemberAll(SqlSession session) {
		//return session.selectList("member.selectMemberAll");
		return mapper.selectMemberAll();
	}

	@Override
	public int insertMember(SqlSession session, MemberDto m) {
		return session.insert("member.insertMember",m);
	}

	@Override
	public int update(SqlSession session, MemberDto memberParam) {
		return session.update("member.update",memberParam);
	}


	@Override
	public MemberDto selectMemberById(String userId) {
		return mapper.selectMemberById(userId);
	}	
}
  • member-mapper.xml
  <!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="member">

 	  	<resultMap id="memberMap" type="com.joo.usedmarket1.dto.MemberDto">
			<id property="user_Id" column="user_id"/>
			<result property="password" column="password"/>
			<result property="userName" column="username"/>
			<result property="age" column="age"/>
			<result property="email" column="email"/>
			<result property="phone" column="phone"/>
			<result property="address" column="address"/>
			<result property="hobby" column="hobby"/>
			<result property="enroll_Date" column="enroll_date"/>
		</resultMap> 


	<select id="selectMemberAll" resultMap="memberMap">
		SELECT * FROM MEMBER
	</select>
	
	<insert id="insertMember">
		INSERT INTO MEMBER VALUES(#{user_Id},#{password},#{username},#{age},#{email},#{phone},#{address},#{hobby},SYSDATE)
	</insert>
	
	<update id="update">
		UPDATE MEMBER 
		   SET 
		        password = #{password},
		        username = #{username},
		        age = #{age},
		        email = #{email},
		        phone = #{phone},
		        address = #{address},
		        hobby = #{hobby}    
		WHERE user_id = #{user_Id}
	</update>
</mapper>
  • memberList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<tr>
			<td>아이디</td>
			<td>이름</td>
			<td>나이</td>
			<td>이메일</td>
			<td>전화번호</td>
			<td>주소</td>
			<td>취미</td>
			<td>등록일</td>
		</tr>
		<c:forEach var="m" items="${members}">
			<tr>
				<td>${m.user_Id}</td>
				<td>${m.username}</td>
				<td>${m.age}</td>
				<td>${m.email}</td>
				<td>${m.phone}</td>
				<td>${m.address}</td>
				<td>${m.hobby}</td>
				<td>${m.enroll_Date}</td>
				<td><button onclick="location.href='${path}/member/edit/${m.user_Id}'" type="button">유저 수정</button></td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>
  • insertMember.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="springform" uri="http://www.springframework.org/tags/form"%> 

<c:set var="path" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>

<style>
	.error{
		color:red;
		font-weight: bolder;
		margin-bottom: 10px;
		width: 1000px;
	}
	.row{
		display:flex;
		flex-direction: column;
		width: 300px;
	}
	#user_Id_{
		margin-bottom: 10px;
	}
</style>

<body>
	<h2>회원가입</h2>
	
	<springform:form modelAttribute="memberDto" name="memberEnrollFrm" action="${path}/member/insertMember.do" method="post">
	<div class="row">
		<springform:input path="user_Id" type="text" placeholder="아이디(4글자이상)" name="user_Id" id="user_Id_"/>
		<springform:errors path="user_Id" cssClass="error"/>
		<springform:input path="password" type="password" placeholder="비밀번호" name="password" id="password_"/>
		<springform:errors path="password" cssClass="error"/>
		<input type="password" placeholder="비밀번호확인" name="password2" id="password2_">
		<springform:input path="username" type="text" placeholder="이름" name="name" id="name_"/>
		<springform:errors path="username" cssClass="error"/>
		<springform:input path="age" type="number" placeholder="나이" name="age" id="age_"/>
		<springform:errors path="age" cssClass="error"/>
		<springform:input path="email" type="email" placeholder="이메일" name="email" id="email_"/>
		<springform:errors path="email" cssClass="error"/>
		
				<springform:input path="phone" type="tel" placeholder="전화번호" name="phone" id="phone_"/>
		<springform:errors path="email" cssClass="error"/>
		
				<springform:input path="address" type="text" placeholder="주소" name="address" id="address_"/>
		<springform:errors path="email" cssClass="error"/>
		
				<springform:input path="hobby" type="text" placeholder="취미" name="hobby" id="hobby_"/>
		<springform:errors path="email" cssClass="error"/>
		
		<input type="submit" value="가입">
		</div>
	</springform:form>
</body>
</html>
  • editForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="springform" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link href="../css/bootstrap.min.css"
	th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<style>
.container {
	max-width: 560px;
}

.error {
	color: red;
	font-weight: bolder;
	margin-bottom: 10px;
	width: 1000px;
}
</style>
</head>
<body>
	<div class="container">
		<div class="py-5 text-center">
			<h2>상품 수정 폼</h2>
		</div>
	<springform:form modelAttribute="memberDto" action="" method="post"> <!-- action 값에 비어있으면, 현재 url 그대로 호출 -->
			<div>
				<label for="id">유저 ID</label> 
				<input type="text" id="id"
					name="user_Id" class="form-control" value="${member.user_Id}"
					readonly>
			</div>


			<label for="itemName">비밀번호</label>
			<springform:input path="password" type="text" id="itemName"
				name="password" class="form-control" value="${member.password}" />
			<springform:errors path="password" cssClass="error" />
	
			<div>
				<label for="price">이름</label>
				<springform:input path="username" type="text" id="price"
					name="username" class="form-control" value="${member.username}" />
				<springform:errors path="username" cssClass="error" />
			</div>
			<div>
				<label for="quantity">나이</label>
				<springform:input path="age" type="text" id="quantity" name="age"
					class="form-control" value="${member.age}" />
				<springform:errors path="age" cssClass="error" />
			</div>
			<div>
				<label for="quantity">이메일</label>
				<springform:input path="email" type="text" id="quantity" name="email"
					class="form-control" value="${member.email}" />
				<springform:errors path="email" cssClass="error" />
			</div>
			<div>
				<label for="quantity">전화번호</label>
				<springform:input path="phone" type="text" id="quantity" name="phone"
					class="form-control" value="${member.phone}" />
				<springform:errors path="phone" cssClass="error" />
			</div>
			<div>
				<label for="quantity">주소</label>
				<springform:input path="address" type="text" id="quantity"
					name="address" class="form-control" value="${member.address}" />
				<springform:errors path="address" cssClass="error" />
			</div>
			<div>
				<label for="quantity">취미</label>
				<springform:input path="hobby" type="text" id="quantity" name="hobby"
					class="form-control" value="${member.hobby}" />
				<springform:errors path="hobby" cssClass="error" />
			</div>
			<div>
				<label for="quantity">등록일</label> <input type="text" id="quantity"
					name="enroll_Date" class="form-control" value="${member.enroll_Date}">
			</div>


			<hr class="my-4">
			<div class="row">
				<div class="col">
					<button class="w-100 btn btn-primary btn-lg" type="submit">저장</button>
				</div>
		
				<div class="col">
					<button onclick="location.href='${path}/member/memberAll'"
						type="button">취소</button>
				</div>
			</div>
		</springform:form>
	</div>
</body>
</html>
profile
우측 상단 햇님모양 클릭하셔서 무조건 야간모드로 봐주세요!!

0개의 댓글