수정
- birthDate 추가
UserDetail
package com.library.bookwave.repository.model;
import java.sql.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
// user_detail_tb
public class UserDetail {
private int userId;
private String email;
private Date birthDate;
private Boolean gender;
private String phone;
private String zip;
private String addr1;
private String addr2;
}
user.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="com.library.bookwave.repository.interfaces.SignUpRepository">
<insert id="createUser">
insert into user_tb(login_id, password, name)
values (#{loginId}, #{password}, #{name})
</insert>
<select id="findById"
resultType="com.library.bookwave.repository.model.User">
select * from user_tb where login_id = #{loginId}
</select>
<insert id="createUserDetail">
insert into user_detail_tb (user_id, email, birth_date, gender,phone, zip, addr1, addr2)
values (#{id}, #{userDetail.email}, #{userDetail.birthDate},
#{userDetail.gender}, #{userDetail.phone}, #{userDetail.zip},
#{userDetail.addr1}, #{userDetail.addr2})
</insert>
<select id="findAll"
resultType="com.library.bookwave.repository.model.UserDetail">
select * from user_detail_tb
</select>
<!-- select 로그인 -->
<select id="findAllByUser"
resultType="com.library.bookwave.repository.model.User">
select * from user_tb where login_id = #{loginId} and password = #{password}
</select>
<!-- ID 찾기 -->
<select id="findByUserId" resultType="com.library.bookwave.repository.model.User">
select * from user_tb where name = #{loginId}
</select>
<!-- update, detete -->
</mapper>
Member.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.library.bookwave.repository.interfaces.MemberRepository">
<select id="readUserId" resultType="com.library.bookwave.repository.model.User">
select * from user_tb where login_id = #{loginId}
</select>
</mapper>
MemberRepository
package com.library.bookwave.repository.interfaces;
import org.apache.ibatis.annotations.Mapper;
import com.library.bookwave.repository.model.User;
@Mapper
public interface MemberRepository {
// ID 중복확인
public User readUserId(String loginId);
}
UserService
package com.library.bookwave.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.library.bookwave.dto.SignUpDTO;
import com.library.bookwave.handler.exception.DataDeliveryException;
import com.library.bookwave.handler.exception.RedirectException;
import com.library.bookwave.repository.interfaces.MemberRepository;
import com.library.bookwave.repository.interfaces.SignUpRepository;
import com.library.bookwave.repository.model.User;
import com.library.bookwave.repository.model.UserDetail;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class UserService {
@Autowired
private final SignUpRepository signUpRepository;
@Autowired
private final MemberRepository memberRepository;
// 회원 가입 처리
// 통합 메서드
@Transactional
public void registerUser(SignUpDTO signUpDTO) {
// user_tb에 사용자 정보 저장
createUser(signUpDTO);
// 저장된 사용자 정보 조회
User user = null;
try {
// dto에서 loginId 가져오기
String loginId = signUpDTO.getLoginId();
// loginId로 User 객체 조회
user = signUpRepository.findById(loginId);
if (user == null) {
throw new DataDeliveryException("사용자를 찾을 수 없습니다.", HttpStatus.NOT_FOUND);
}
} catch (DataAccessException e) {
System.out.println("registerUser");
throw new DataDeliveryException("오류로 사용자 조회에 실패했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
throw new RedirectException("알 수 없는 오류가 발생했습니다.", HttpStatus.SERVICE_UNAVAILABLE);
}
// user_detail_tb에 사용자 상세 정보 저장
createUserDetail(user.getId(), signUpDTO);
}
// TODO ID 중복확인
public User readUserId(String loginId) {
return memberRepository.readUserId(loginId);
}
/**
* user_tb에 사용자 정보 삽입 메서드
*
* @param signUpDTO 사용자 정보가 담긴 DTO
*/
private void createUser(SignUpDTO signUpDTO) {
try {
int result = signUpRepository.createUser(signUpDTO.toUser());
if (result != 1) {
throw new DataDeliveryException("회원가입에 실패했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (DataAccessException e) {
System.out.println("createUser");
e.printStackTrace();
throw new DataDeliveryException("오류로 회원가입에 실패했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
e.printStackTrace();
throw new RedirectException("알 수 없는 오류가 발생했습니다.", HttpStatus.SERVICE_UNAVAILABLE);
}
}
/**
* user_detail_tb에 사용자 상세 정보 삽입 메서드
*
* @param userId 사용자 ID
* @param signUpDTO 사용자 상세 정보가 담긴 DTO
*/
private void createUserDetail(Integer id, SignUpDTO signUpDTO) {
try {
UserDetail userDetail = signUpDTO.detailUser();
System.err.println(userDetail);
int result = signUpRepository.createUserDetail(id, userDetail);
if (result != 1) {
throw new DataDeliveryException("사용자 상세 정보 저장에 실패했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (DataAccessException e) {
e.printStackTrace();
throw new DataDeliveryException("오류로 사용자 상세 정보 저장에 실패했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
throw new RedirectException("알 수 없는 오류가 발생했습니다.", HttpStatus.SERVICE_UNAVAILABLE);
}
}
}// end of main
UserRestController
package com.library.bookwave.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.library.bookwave.repository.model.User;
import com.library.bookwave.service.UserService;
import lombok.RequiredArgsConstructor;
@RestController
@RequestMapping("/controller-user")
@RequiredArgsConstructor
public class UserRestController {
@Autowired
private UserService userService;
// 주소
// http://localhost:8080/controller-user/check-userId
// ID 중복 확인
@GetMapping("/check-userId")
@ResponseBody
public boolean getUserId(@RequestParam(name = "loginId") String loginId) {
//return userService.confirmUid(loginId);
System.out.println(loginId);
boolean isUse = userService.readUserId(loginId) == null ? true : false;
return isUse;
}
// // test
// @GetMapping("/check-loginId")
// public boolean getUserId(@RequestParam(name = "loginId") String loginId) {
// // return userService.getUserId(loginId);
// boolean isUse = userService.confirmUid(loginId) == null ? true : false;
// return isUse;
// }
}
SignUpDTO
package com.library.bookwave.dto;
import java.sql.Date;
import java.util.Calendar;
import com.library.bookwave.repository.model.User;
import com.library.bookwave.repository.model.UserDetail;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
// 회원가입 DTO
public class SignUpDTO {
private String loginId; // 아이디
private String password;
private String name;
private String email; // 이메일
private String email1;
private String email2;
private Integer year; // 생년월일 - 년
private Integer month; // 생년월일 - 월
private Integer day; // 생년월일 - 일
private Boolean gender; // 성별 // 대문자, 소문자 구분!
private String phone; // 전화번호
private String phone1;
private String phone2;
private String phone3;
private String zip; // 우편번호
private String addr1; // 주소(시/도)
private String addr2; // 주소(상세주소)
public User toUser() {
return User.builder()
.loginId(this.loginId)
.password(this.password)
.name(this.name)
.build();
}
public UserDetail detailUser() {
return UserDetail.builder()
.email( this.email1 + "@" +this.email2 )
.birthDate(Date.valueOf(year + "-" + month + "-" + day))
.gender(this.gender)
.phone(this.phone1+"-"+this.phone2 + "-" + this.phone3)
.zip(this.zip)
.addr1(this.addr1)
.addr2(this.addr2)
.build();
}
}
signUp.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>회원가입</title>
<link rel="stylesheet" href="/css/signUp.css" type="text/css" />
</head>
<body>
<div class="signup-container">
<h2>회원가입</h2>
<form action="/user/sign-up" method="post">
<div class="form-group">
<label for="loginId">아이디</label> <input style="width: 81%"
type="text" class="loginId" placeholder="아이디 입력" id="loginId"
name="loginId" maxlength="12" required />
<button type="button" class="check-id">중복체크</button>
<p class="result-uid"></p>
</div>
<div class="form-group">
<label for="password">비밀번호</label> <input type="password"
class="form-control" placeholder="비밀번호 입력" id="password"
name="password" required />
</div>
<div class="form-group">
<label for="password-check">비밀번호 확인</label> <input type="password"
class="form-control" placeholder="비밀번호 재입력" id="password-check"
name="password-check" required />
</div>
<div class="form-group">
<label for="name">이름</label> <input type="text"
class="form-control" placeholder=" 이름을 입력해주세요" id="name" name="name"
required />
</div>
<br />
<div class="form-group2">
<label for="phone">전화번호 </label>
<div class="phone">
<select name="phone1">
<option>010</option>
<option>02</option>
<option>031</option>
<option>051</option>
</select> - <input type="text" name="phone2" size="5" required maxlength="4" />
- <input type="text" name="phone3" size="5" required maxlength="4" />
</div>
</div>
<!-- 생년월일 입력 필드 추가 -->
<div class="form-group2">
<label for="birthDate">생년월일:</label>
<div class="birthDate">
<select name="year" required >
<option>년도</option>
<%
for (int i = 1900; i <= 2024; i++) {
%>
<option value="<%=i%>"><%=i%></option>
<%
}
%>
</select> <select name="month" required style="margin: 5px">
<option >월</option>
<%
for (int i = 1; i <= 12; i++) {
%>
<option value="<%=i%>"><%=i%></option>
<%
}
%>
</select><select name="day" required style="margin: 5px " >
<option >일</option>
<%
for (int i = 1; i <= 31; i++) {
%>
<option value="<%=i%>"><%=i%></option>
<%
}
%>
</select>
</div>
</div>
<br />
<div class="form-group">
<label for="zip">주소(우편번호):</label> <input type="text"
class="form-control" placeholder=" zip" id="zip" name="zip"
required />
</div>
<br />
<div class="form-group2">
<label for="email">이메일:</label> <input type="text"
class="form-control" placeholder=" email" id="email" name="email1"
required /> <span id="email2" class="input-group-text">@</span>
<select name="email2">
<option value="naver.com">naver.com</option>
<option value="gmail.com">gmail.com</option>
<option value="nate.com">nate.com</option>
<option value="hanmail.net">hanmail.net</option>
<option value="daum.net">daum.net</option>
</select>
</div>
<br />
<br /> <input class="check" type="radio" name="gender"
value="false" checked />남자 <input class="check"
type="radio" name="gender" value="true" />여자 <br /> <br />
<br />
<div>
<button type="submit" class="btn">회원가입</button>
</div>
</form>
</div>
</body>
<script src="/js/signup.js"></script>
</html>
signup.js
const resultUid = document.querySelector(".result-uid"); // 에러 메세지
const btnId = document.querySelector(".check-id"); // 중복체크 버튼
const inputId = document.querySelector(".loginId"); // 아이디
const btnSubmit = document.getElementById("btn"); // 회원가입 버튼
const reUid = /^[a-z]+[a-z0-9]{5,12}$/g; // 조건
let isUidOk = false;
btnId.addEventListener("click", function () {
const inputId = loginId.value.trim(); // 입력 필드의 값 가져오기
console.log(inputId);
const url = "/controller-user/check-userId?loginId=" + inputId;
console.log("url", url);
fetch(url)
.then((response) => response.json()) // 응답을 JSON 형식으로 반환
.then((isUse) => {
console.log("결과 확인 ", isUse);
if (isUse) {
resultUid.textContent = "사용 가능한 ID입니다.";
resultUid.style.color = 'green';
} else {
resultUid.textContent = "중복된 ID입니다";
resultUid.style.color = 'red';
}
})
.catch((error) => {
console.log("error ", error);
resultUid.textContent = "잘못된 요청입니다.";
});
});
'My Project > 도서 관리 프로그램 (final project)' 카테고리의 다른 글
6일차 - 로그인 소셜 로그인 api 연결 (1) | 2024.09.09 |
---|---|
5일차 - 기본 로그인 완료 (0) | 2024.09.05 |
5일차 - 회원가입 주소 api 연결, 유효성 및 정규화 (0) | 2024.09.04 |
2일차 - 회원가입 요청 처리 완료 (0) | 2024.08.28 |
1일차 - 회원가입 화면 구성 , 회원가입 요청 처리 (1) | 2024.08.27 |