스프링부트 블로그 만들기 – 8강 회원정보
회원정보 조회
1.UserController.java에서 회원정보 조회를 위한 메서드를 만들어준다.
@GetMapping("/user/{id}")
public String userInfo(@PathVariable int id) {
return "user/updateForm";
}
2.src/main/webapp/WEB-INF/views/user 폴더 안에 updateForm.jsp 파일을 만들어 세션에 있는 회원정보 데이터를 가지고 온다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp"%>
<div class="container p-4 w-25 bg-light rounded shadow">
<h5 style="font-family: 'IBM Plex Sans KR', sans-serif; margin-bottom: 30px;">회원정보</h5>
<form>
<div class="form-group">
<input type="text" value="${sessionScope.principal.username}" class="form-control"
placeholder="Enter username" required="required" maxlength="20" readonly="readonly">
</div>
<div class="form-group">
<input type="password" value="${sessionScope.principal.password}" class="form-control"
placeholder="Enter password" required="required" maxlength="20">
</div>
<div class="form-group">
<input type="email" value="${sessionScope.principal.email}" class="form-control"
placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary col-md-4"
style="margin-top: 30px;">회원수정</button>
</form>
</div>
<%@ include file="../layout/footer.jsp"%>
회원정보 조회에 세션에 있는 데이터를 가지고 오면 유효성 검사(validation) 을 하지 않아도 되요!!
회원정보 수정
1.updateForm.jsp에서 password UI를 없애준다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp"%>
<div class="container p-4 w-25 bg-light rounded shadow">
<h5
style="font-family: 'IBM Plex Sans KR', sans-serif; margin-bottom: 30px;">회원정보</h5>
<form onsubmit="update(event,${sessionScope.principal.id})">
<div class="form-group">
<input type="text" value="${sessionScope.principal.username}"
class="form-control" placeholder="Enter username" maxlength="20"
readonly="readonly">
</div>
<div class="form-group">
<input type="email" id="email"
value="${sessionScope.principal.email}" class="form-control"
placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary col-md-4"
style="margin-top: 30px;">회원수정</button>
</form>
</div>
<%@ include file="../layout/footer.jsp"%>
비밀번호 해시값으로 들어오기 때문에 여기서 수정하지 않고 따로 빼주는 것이 좋습니다.
2.UserController.java에서 회원정보 수정하기 메서드를 만들어준다.
@PutMapping("/user/{id}")
public @ResponseBody CMRespDto<String> update(@PathVariable int id, @Valid @RequestBody UserUpdateDto dto, BindingResult bindingResult) {
//@RequestBody => 자바스크립트로 받기
//공통로직
//유효성검사
if (bindingResult.hasErrors()) {
Map<String, String> errorMap = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errorMap.put(error.getField(), error.getDefaultMessage());
}
throw new MyAsyncNotFoundException(errorMap.toString());
}
//인증 체크
User principal = (User) session.getAttribute("principal");
if (principal == null) {
throw new MyAsyncNotFoundException("인증이 되지 않았습니다.");
}
//권한 체크
if (principal.getId() != id) {
throw new MyAsyncNotFoundException("회원정보를 수정할 권한이 없습니다.");
}
//핵심로직(세션에서 데이터 가져온다)
principal.setEmail(dto.getEmail());
session.setAttribute("principal", principal); //세션값 변경
userRepository.save(principal);
return new CMRespDto<String>(1,"성공",null);
}
3.자바스크립트로 수정하기 기능을 구현하고 회원수정 버튼을 클릭하면 update() 함수가 호출되도록 만든다.
<div class="container p-4 w-25 bg-light rounded shadow">
<h5
style="font-family: 'IBM Plex Sans KR', sans-serif; margin-bottom: 30px;">회원정보</h5>
<form onsubmit="update(event,${sessionScope.principal.id})">
<div class="form-group">
<input type="text" value="${sessionScope.principal.username}"
class="form-control" placeholder="Enter username" maxlength="20"
readonly="readonly">
</div>
<div class="form-group">
<input type="email" id="email"
value="${sessionScope.principal.email}" class="form-control"
placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary col-md-4"
style="margin-top: 30px;">회원수정</button>
</form>
</div>
<script>
async function update(event, id){
event.preventDefault();
let userUpdateDto = {
email: document.querySelector("#email").value,
};
let response = await fetch("http://localhost:8000/user/"+id, {
method: "put",
body: JSON.stringify(userUpdateDto), // json 데이터 전송
headers: {
"Content-Type": "application/json; charset=utf-8"
}
});
let parseResponse = await response.json();
if(parseResponse.code == 1){
alert("업데이트 성공");
location.href="/";
}else{
alert("업데이트 실패 : " + parseResponse.msg);
}
}
</script>

