반응형
MemberController.java
package com.example.controller;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.bind.annotation.RequestParam;
import com.example.domain.MemberVO;
import com.example.mapper.MemberMapper;
import com.example.service.MemberService;
import com.example.util.Script;
import lombok.Setter;
import lombok.extern.java.Log;
@Controller
@RequestMapping("/member/*")
@Log
public class MemberController {
@Setter(onMethod_ = @Autowired)
private MemberService memberService;
@GetMapping("/join")
public String join() {
// http://localhost:8000/member/join
return "member/join";
}
@PostMapping("/join")
public String join(MemberVO memberVO) {
// 회원가입 날짜 셋팅
memberVO.setRegDate(new Date());
String passwd = memberVO.getPasswd();
String hashPasswd = BCrypt.hashpw(passwd, BCrypt.gensalt());
memberVO.setPasswd(hashPasswd);
System.out.println(memberVO.toString());
// 회원가입 처리함
memberService.register(memberVO);
return "redirect:/member/login";
}
@GetMapping("/login")
public String login() {
return "member/login";
}
@PostMapping("/login")
public ResponseEntity<String> login(String id, String passwd, HttpSession session) {
MemberVO memberVO = memberService.getMemberById(id);
boolean isSamePasswd = false;
String message = "";
if (memberVO != null) { // 일치하는 아이디 있음
isSamePasswd = BCrypt.checkpw(passwd, memberVO.getPasswd());
if (!isSamePasswd) { // 패스워드 일치하지 않음
message = "패스워드가 일치하지 않습니다.";
}
} else { // 일치하는 아이디가 없음
message = "존재하지 않는 아이디 입니다.";
}
if (memberVO == null || isSamePasswd == false) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.back(message);
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
}
//==============================
// 로그인 성공 시, 로그인 인증하기
session.setAttribute("memberVO", memberVO);
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/"); // redirect 경로 지정
// "/"로 리다이렉트
// 리다이렉트일 경우 HttpStatus.FOUND 지정해야 함
return new ResponseEntity<String>(headers, HttpStatus.FOUND);
} // login
@GetMapping("/logout")
public ResponseEntity<String> logout(HttpSession session) {
// 세션 초기화
session.invalidate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.href("로그아웃 되었습니다.", "/");
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
}
@GetMapping("/remove")
public String remove() {
return "member/remove";
}
@PostMapping("/remove")
public ResponseEntity<String> remove(String passwd, HttpSession session) {
MemberVO memberVO = (MemberVO) session.getAttribute("memberVO");
boolean isSamePasswd = BCrypt.checkpw(passwd, memberVO.getPasswd());
if (!isSamePasswd) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.back("패스워드가 일치하지 않습니다.");
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
}
// 회원탈퇴(삭제)처리
memberService.removeMemberById(memberVO.getId()); // 테이블 레코드 삭제
session.invalidate(); // 세션 초기화
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.href("회원탈퇴가 정상적으로 처리되었습니다.", "/");
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
} // remove post
@GetMapping("/modify")
public String modify() {
// 회원 본인이 맞는지 패스워드 입력화면을 응답으로 주기
return "member/modifyPasswd";
}
@PostMapping("/modifyValid")
public ResponseEntity<String> modifyValid(String passwd, HttpSession session) {
MemberVO memberVO = (MemberVO) session.getAttribute("memberVO");
boolean isSamePasswd = BCrypt.checkpw(passwd, memberVO.getPasswd());
if (!isSamePasswd) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.back("패스워드가 일치하지 않습니다.");
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
}
// 비밀번호 일치할때
UUID uuid = UUID.randomUUID();
String strUuid = uuid.toString();
// 서버가 현재 비밀번호 일치하는 사용자임을 기억하기위해 uuid 문자열을 세션에 저장함
session.setAttribute("uuid", strUuid);
// 회원정보수정 폼 화면을 볼 수 있도록 해당 요청주소로 리다이렉트 시키기
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/member/modifyForm?uuid=" + strUuid); // redirect 경로 지정
// "/"로 리다이렉트
// 리다이렉트일 경우 HttpStatus.FOUND 지정해야 함
return new ResponseEntity<String>(headers, HttpStatus.FOUND);
} // modifyForm post
@GetMapping("/modifyForm")
public String modifyForm(String uuid, HttpSession session) {
String sessUuid = (String) session.getAttribute("uuid");
if (uuid == null || !uuid.equals(sessUuid)) {
return "redirect:/member/modify";
}
session.removeAttribute("uuid");
return "member/modifyForm";
}
@PostMapping("/modifyProcess")
public String modifyProcess(MemberVO memberVO, HttpSession session) {
String hashPasswd = BCrypt.hashpw(memberVO.getPasswd(), BCrypt.gensalt());
memberVO.setPasswd(hashPasswd);
// 테이블에 회원정보 수정 처리
memberService.modifyMemberById(memberVO);
// 로그인 유지용 세션 정보 수정하기
MemberVO dbMemberVO = memberService.getMemberById(memberVO.getId());
session.setAttribute("memberVO", dbMemberVO);
return "redirect:/member/info";
} // modifyProcess post
@GetMapping("/info")
public String info() {
return "member/info";
}
}
회원탈퇴 구현
@Delete("DELETE FROM member WHERE id = #{id}")
int deleteMemberById(String id);
@PostMapping("/remove")
public ResponseEntity<String> remove(String passwd, HttpSession session) {
MemberVO memberVO = (MemberVO) session.getAttribute("memberVO");
boolean isSamePasswd = BCrypt.checkpw(passwd, memberVO.getPasswd());
if (!isSamePasswd) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.back("패스워드가 일치하지 않습니다.");
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
}
// 회원탈퇴(삭제)처리
memberService.removeMemberById(memberVO.getId()); // 테이블 레코드 삭제
session.invalidate(); // 세션 초기화
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html; charset=utf-8");
String str = Script.href("회원탈퇴가 정상적으로 처리되었습니다.", "/");
return new ResponseEntity<String>(str, headers, HttpStatus.OK);
} // remove post
public int removeMemberById(String id) {
return memberMapper.deleteMemberById(id);
}
remove.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<!-- App -->
<div id="app">
<%-- include header.jsp --%>
<jsp:include page="/WEB-INF/views/include/header.jsp" />
<div class="container">
<!-- Breadcrumbs -->
<nav>
<div class="nav-wrapper cyan">
<div class="col s12">
<a href="/" class="breadcrumb">홈</a>
<a href="/member/remove" class="breadcrumb">회원탈퇴</a>
</div>
</div>
</nav>
<!-- end of Breadcrumbs -->
<!-- Forms -->
<div class="row">
<h4 class="center-align">회원탈퇴</h4>
<hr style="margin-bottom: 50px;">
<form id="frm" class="col s12 l6 offset-l3" action="/member/remove" method="post">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">assignment_ind</i>
<input type="text" id="member_id" class="validate" name="id" value="${ memberVO.id }" disabled>
<label for="member_id">아이디</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input type="password" id="password" class="validate" name="passwd">
<label for="password">비밀번호</label>
</div>
</div>
<div class="row center-align">
<button type="submit" class="btn waves-effect waves-light">
회원탈퇴하기
<i class="material-icons right">directions_run</i>
</button>
</div>
</form>
</div>
<!-- end of Forms -->
</div>
<!-- end of Container -->
<!-- Footer -->
<%-- include footer.jsp --%>
<jsp:include page="/WEB-INF/views/include/footer.jsp" />
<!-- end of Footer -->
</div>
<!-- end of App -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
const sideNav = document.querySelector('.sidenav');
M.Sidenav.init(sideNav, {});
</script>
<script>
var frm = document.querySelector('#frm');
frm.addEventListener('submit', function (event) {
// 기본동작이 있는 대표적인 태그 2개 : a태그, form태그
event.preventDefault(); // 기본동작 막기
var isRemove = confirm('정말 회원탈퇴 하시겠습니까?');
if (!isRemove) {
return;
}
frm.submit();
});
</script>
</body>
</html>
회원정보 수정
@Update("UPDATE member "
+ "SET passwd = #{passwd}, name = #{name}, email = #{email}, recv_email = #{recvEmail} "
+ "WHERE id = #{id}")
void updateMemberById(MemberVO memberVO);
public void modifyMemberById(MemberVO memberVO) {
memberMapper.updateMemberById(memberVO);
}
반응형
'Back-End > Java' 카테고리의 다른 글
[Spring] Legacy Project 아이디 중복 확인하기 (0) | 2021.06.10 |
---|---|
[Spring] Legacy Project Handler intercepor 사용법 (0) | 2021.06.10 |
[Spring] Legacy Project DB연동 및 한글깨짐 해결 (0) | 2021.06.09 |
[Spring] Legacy Project Controller 설정 및 MVC 구조 (0) | 2021.06.09 |
[Spring] Legacy Project 오라클 연동하기 (0) | 2021.06.08 |