ㅁ views/member에 myinfo.jsp를 만든다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#profileImg{
width:250px;
height:250px;
border:1px solid lightgray;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="container p-3">
<!-- Header, Nav start -->
<jsp:include page="/WEB-INF/views/common/header.jsp"/>
<!-- Header, Nav end -->
<!-- Section start -->
<section class="row m-3" style="min-height: 500px">
<div class="container border p-5 m-4 rounded">
<h2 class="m-4">마이페이지</h2>
<br>
<div align="center">
<img id="profileImg" src="../../../resources/images/defaultProfile.png" onclick="$('#profileImgFile').click();">
<input type="file" id="profileImgFile" style="display:none;">
</div>
<form action="" method="post" onsubmit="">
<div class="form-group">
<label for="userId">* ID :</label>
<input type="text" class="form-control" id="userId" name="" value="user01" readonly><br>
<label for="userName">* Name :</label>
<input type="text" class="form-control" id="userName" name="" value="홍길동"><br>
<label for="email"> Email :</label>
<input type="email" class="form-control" id="email" name="" value="user01@br.or.kr"><br>
<label for="phone"> Phone :</label>
<input type="tel" class="form-control" id="phone" name="" value="010-1111-2222"><br>
<label for="address"> Address :</label>
<input type="text" class="form-control" id="address" name="" value="서울 양천구"><br>
<label for=""> Gender : </label>
<input type="radio" name="" id="Male" value="M" checked>
<label for="Male">남자</label>
<input type="radio" name="" id="Female" value="F">
<label for="Female">여자</label><br>
</div>
<br>
<div class="btns" align="center">
<button type="submit" class="btn btn-primary">수정하기</button>
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#deleteForm">회원탈퇴</button>
</div>
</form>
</div>
</section>
<!-- Section end -->
<!-- Footer start -->
<jsp:include page="/WEB-INF/views/common/footer.jsp"/>
<!-- Footer end -->
</div>
<!-- 회원탈퇴 버튼 클릭시 보여질 Modal -->
<div class="modal" id="deleteForm">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">회원탈퇴</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body" align="center">
<b>
탈퇴 후 복구가 불가능합니다. <br>
정말로 탈퇴 하시겠습니까?
</b>
<form action="" method="post">
비밀번호 :
<input type="password" name="" required>
<button type="submit" class="btn btn-danger">탈퇴하기</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
- 마이페이지_myinfo.html에서 body태그를 복붙, 스타일 태그를 복붙했다.
ㅁ header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!-- Bootstrap 사용을 위한 CDN -->
<!-- ------------------------- -->
<style>
header{height: 50px}
header a{color:black;}
header .profile-img{width:30px;}
</style>
<script>
if('${alertMsg}' != ''){
alert('${alertMsg}');
if('${historyBackYN}' == 'Y'){
history.back();
}
}
</script>
<header class="row m-3">
<div class="col-3 d-flex justify-content-center align-items-center">
<a href=""><img src="${ contextPath }/resources/images/goodee_logo.png" width="100px"></a>
</div>
<div class="col-5"></div>
<div class="col-4 d-flex justify-content-center align-items-center">
<c:choose>
<c:when test="${ empty loginUser }">
<!-- case1. 로그인전 -->
<a href="${contextPath}/member/signup.do">회원가입</a> |
<a href="#" data-toggle="modal" data-target="#loginModal">로그인</a>
</c:when>
<c:otherwise>
<!-- case2. 로그인후 -->
<div>
<img class="profile-img" src="${ contextPath }<c:out value='${loginUser.profileURL}' default='/resources/images/defaultProfile.png' />">
<a href="${contextPath}/member/myinfo.do">${loginUser.userName}님</a> |
<a href="${contextPath}/member/signout.do">로그아웃</a>
</div>
</c:otherwise>
</c:choose>
</div>
</header>
<nav class="navbar m-3 navbar-expand-sm bg-dark navbar-dark d-flex justify-content-center">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">공지사항</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">일반게시판</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">사진게시판</a>
</li>
</ul>
</nav>
<!-- 로그인 클릭 시 뜨는 모달 (기존에는 안보이다가 위의 a 클릭시 보임) -->
<div class="modal fade" id="loginModal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Login</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form action="${contextPath}/member/signin.do" method="post">
<!-- Modal Body -->
<div class="modal-body">
<label for="userId" class="mr-sm-2">ID :</label>
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="Enter ID" id="userId" name="userId" required> <br>
<label for="userPwd" class="mr-sm-2">Password:</label>
<input type="password" class="form-control mb-2 mr-sm-2" placeholder="Enter password" id="userPwd" name="userPwd" required>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit" class="btn btn-primary">로그인</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">취소</button>
</div>
</form>
</div>
</div>
</div>
- ~님해서 로그인한 회원의 이름이 노출되는 a태그가 있다.
여기에 경로를 작성한다. 마이페이지로 이동하는.
ㅁ MemberController
package com.br.spring.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.br.spring.dto.MemberDto;
import com.br.spring.service.MemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequestMapping("/member")
@RequiredArgsConstructor
@Controller
public class MemberController {
private final MemberService memberService;
private final BCryptPasswordEncoder bcryptPwdEncoder;
@PostMapping("/signin.do")
public void signin(MemberDto m, HttpServletResponse response, HttpSession session, HttpServletRequest request) throws IOException {
MemberDto loginUser = memberService.selectMember(m);
// 로그인 성공시 => 세션에 회원정보를 담고, alert와 함께 메인 페이지로 이동
// 로그인 실패시 => alert와 함께 기존에 보던 페이지 유지(아이디, 비번 입력하는 로그인 폼 유지. 작성하던 입력데이터도 그대로.)
// script문을 응답데이터로 돌려줘서 흐름제어
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>");
if(loginUser != null && bcryptPwdEncoder.matches(m.getUserPwd(), loginUser.getUserPwd())) { // 로그인 성공
session.setAttribute("loginUser", loginUser);
out.println("alert('" + loginUser.getUserName() + "님 환영합니다~');");
out.println("location.href = '" + request.getHeader("referer") + "';"); // 메인페이지가 아닌 이전에 보던 페이지로 이동
}else { // 로그인 실패
out.println("alert('로그인에 실패하였습니다. 아이디 및 비밀번호를 다시 확인해주세요.');");
out.println("history.back();"); // modal이 띄워진 상태였으면 modal도 유지된다.
}
out.println("</script>");
}
@GetMapping("/signout.do")
public String signout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
@GetMapping("/signup.do")
public void signupPage() { } //WEB-INF/views/member/signup.jsp
@ResponseBody
@GetMapping("/idcheck.do")
public String idCheck(String checkId) {
return memberService.selectUserIdCount(checkId) == 0 ? "YYYY" : "NNNN";
}
@PostMapping("/insert.do")
public String signup(MemberDto m, RedirectAttributes rdAttributes) {
log.debug("암호화 전 member: {}", m);
m.setUserPwd( bcryptPwdEncoder.encode(m.getUserPwd()) );
log.debug("암호화 후 member: {}", m);
int result = memberService.insertMember(m);
// 성공시 alert와 함께 메인페이지 이동
// 실패시 alert와 함께 기존에 작업중이던 페이지 유지
if(result > 0) {
rdAttributes.addFlashAttribute("alertMsg", "성공적으로 회원가입 되었습니다.");
}else {
rdAttributes.addFlashAttribute("alertMsg", "회원가입에 실패하였습니다.");
rdAttributes.addFlashAttribute("historyBackYN", "Y");
}
return "redirect:/";
}
@GetMapping("/myinfo.do")
public void myinfoPage() {}
}
- myinfoPage() 메소드르르 만들었다.
굳이 응답 뷰를 반환할 필용 ㅓㅄ이 void로 둘 수 있다.
ㅁ myinfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#profileImg{
width:250px;
height:250px;
border:1px solid lightgray;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="container p-3">
<!-- Header, Nav start -->
<jsp:include page="/WEB-INF/views/common/header.jsp"/>
<!-- Header, Nav end -->
<!-- Section start -->
<section class="row m-3" style="min-height: 500px">
<div class="container border p-5 m-4 rounded">
<h2 class="m-4">마이페이지</h2>
<br>
<div align="center">
<img id="profileImg" src="${contextPath}<c:out value='${loginUser.profileURL}' default='/resources/images/defaultProfile.png' />" onclick="$('#profileImgFile').click();">
<input type="file" id="profileImgFile" style="display:none;">
</div>
<form action="" method="post" id="myinfo_form">
<div class="form-group">
<label for="userId">* ID :</label>
<input type="text" class="form-control" id="userId" name="" value="${ loginUser.userId }" readonly><br>
<label for="userName">* Name :</label>
<input type="text" class="form-control" id="userName" name="" value="${ loginUser.userName }"><br>
<label for="email"> Email :</label>
<input type="email" class="form-control" id="email" name="" value="${ loginUser.email }"><br>
<label for="phone"> Phone :</label>
<input type="tel" class="form-control" id="phone" name="" value="${ loginUser.phone}"><br>
<label for="address"> Address :</label>
<input type="text" class="form-control" id="address" name="" value="${ loginUser.address }"><br>
<label for=""> Gender : </label>
<input type="radio" name="" id="Male" value="M">
<label for="Male">남자</label>
<input type="radio" name="" id="Female" value="F">
<label for="Female">여자</label><br>
<script>
$(function(){
$("#myinfo_form :radio").filter("[value=${loginUser.gender}]").attr("checked", true);
})
</script>
</div>
<br>
<div class="btns" align="center">
<button type="submit" class="btn btn-primary">수정하기</button>
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#deleteForm">회원탈퇴</button>
</div>
</form>
</div>
</section>
<!-- Section end -->
<!-- Footer start -->
<jsp:include page="/WEB-INF/views/common/footer.jsp"/>
<!-- Footer end -->
</div>
<!-- 회원탈퇴 버튼 클릭시 보여질 Modal -->
<div class="modal" id="deleteForm">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">회원탈퇴</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body" align="center">
<b>
탈퇴 후 복구가 불가능합니다. <br>
정말로 탈퇴 하시겠습니까?
</b>
<form action="" method="post">
비밀번호 :
<input type="password" name="" required>
<button type="submit" class="btn btn-danger">탈퇴하기</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
- value값들을 다 loginUser에서 불러온다.
- 성별도 checked로 명시적으로 써있는걸 지운다.
현재 로그인한 회원의 성별에 따라서 둘 중에 하나가 체크된 상태로 보여지게끔 스크립트로 작성한다.
- form 요소에서 onsubmit 속성은 지운다.
id를 추가한다. myinfo_form.
언더바는 더블클릭하면 언더바 포함해서 전체선택됨.
대쉬는 더블클릭하면 단어만 선택됨.
- 공백은 후손선택자다. :은 타입선택자다.
- <img id="profileImg" src="../../../resources/images/defaultProfile.png" onclick="$('#profileImgFile').click();">에서
- <img id="profileImg" src="${contextPath}<c:out value='${loginUser.profileURL}' default='/resources/images/defaultProfile.png' />" onclick="$('#profileImgFile').click();">
ㅁ 서버키고 오른쪽 위의 이름을 눌러서 마이페이지로 이동
- db에 저장되어있던 데이터가 보여진다.