회원정보 수정하기

네브바에 회원정보 클릭시 회원정보 보이는 페이지가기

  • <li class="nav-item"><a class="nav-link" href="/user/updateForm">회원정보</a></li>

 

 

1.

[UserController]

@GetMapping("/user/updateForm")
public String updateForm() {
    return "user/updateForm";
}

 

 

 

2. return "user/updateForm"; 뷰페이지 만들기

 

[updateForm.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- ../layput 는 user보다 한 칸위의 폴더라는 뜻  -->
<%@ include file="../layout/header.jsp"%>

<div class="container">

    <form>
    	<input type="hidden" id="id" value="${principal.user.id}"/> 
        <div class="form-group">
            <label for="username">UserName : </label> 
            <input type="text" value="${principal.user.username }" class="form-control" placeholder="Enter UserName" id="username" readonly>
        </div>

        <div class="form-group">
            <label for="pwd">Password : </label> 
            <input type="password" class="form-control" placeholder="Enter password" id="password">
        </div>

        <div class="form-group">
            <label for="email">Email : </label> 
            <input type="email" value="${principal.user.email }"  class="form-control" placeholder="Enter email" id="email">
        </div>
    </form>
	<button id="btn-update" class="btn btn-primary">회원수정 완료</button>
</div>

<script src="/js/user.js"></script>
<%@ include file="../layout/footer.jsp"%>
  • <input type="hidden" id="id" value="${principal.user.id}"/> 

유저 id를 hidden값으로 넣은이유는 수정 시 ajax에서 유저의 id값을 넘겨주어 어떤 유저인지 알기위해

username을 넘겨주면 안되나? username은 수정안해서 넘길 필요가 없음

 

  • userName 과 email은 input태그 value값을 넣어 화면에 보이도록한다 
  • userName 은 수정못하게 readonly 
  • password에는 화면에 보이면 안되니까 value값을 넣지않는게 좋다

 

 

 

여기서 다시 알아야할 점!  principal

세션에 저장된 로그인의 객체가 principal에 저장되어있다.

 

[header.jsp]

<sec:authorize access="isAuthenticated()">
        <sec:authentication property="principal" var="principal"/>
</sec:authorize>

변수 var="principal" 에 넣고 갖다쓰는데 이 principal은 [ PrincipalDetail ] 이다.

[PrincipalDetail] 에는 User객체가 있다.

@Getter
public class PrincipalDetail implements UserDetails{
	private User user; // 콤포지션( 객체를 들고 있는)
...

 

그래서 principal.user 하면 user객체에 접근할 수 있고 

principal.user.username 하면 user객체의 username에 접근이 가능하다.

 

 

 

principal를 써서 username의 value값에 넣어준다  (password 빼고 나머지 email 도 value값을 넣어준다.)

 

  • user객체의 username에 접근

<input type="text" value="${principal.user.username }" class="form control" placeholder="Enter UserName" id="username" readonly>

 

  • user객체의 email에 접근

<input type="email" value="${principal.user.email }"  class="form-control" placeholder="Enter email" id="email">

 

 

 

 

- 회원정보 페이지 결과화면

 

 

 

 

이제 회원수정 완료 버튼을 누르면 자바스크립트 ajax를 이용해 수정한다. 

  • <button id="btn-update" class="btn btn-primary">회원수정 완료</button>

 

[user.js]

let index = {
	init: function() {
		$("#btn-update").on("click", () => { 
			this.update();
		});
	},
    
    //회원 수정(update)
	update: function() {
		let data = {
			password: $("#password").val(),
			email: $("#email").val()
		}
		$.ajax({
			//회원수정 수행 요청
			type:"PUT",
			url:"/user",
			data:JSON.stringify(data), // http body데이터 (마임데이터가 필요)
			contentType:"application/json; charset=utf-8", // body데이터가 어떤 타입인지(MIME)
			dataType: "json" //응답을 json으로 받음. 응답이 왔을때 기본적으로 모든것은 문자열 String. (만약 생긴게 json이라면 -> 자바스크립트 object로 변경)
		}).done(function(resp){
			alert("회원수정이 완료되었습니다.");
			//console.log(resp);
			location.href="/"; 
		}).fail(function(error){
			alert(JSON.stringify(error));
			});
	},
}

 

update: function() {
    let data = {
        id: $("#id").val(),
        password: $("#password").val(),
        email: $("#email").val()
}

수정을 못하는 username은 .val()값을 못넣지만 어떤 유저인지는 알아야하니까 유저의 id값을 넣어준다

그래서 뷰페이지에 user id 값을 hidden으로 넣어줌 <input type="hidden" id="id" value="${principal.user.id}"/> 

 

 

 

데이터를 담고 url:"/user", 주소인 Controller 로 이동

 

 

4. UserApiController

//회원가입 수정
@PutMapping("/user")
public ResponseDto<Integer> update(@RequestBody User user){ //@RequestBody로 받아야 json형태로 받음
    userService.회원수정(user);
    return new ResponseDto<Integer>(HttpStatus.OK.value(),1);
}

 

 

 

회원수정() 메서드 만든다

 

5. UserService

@Transactional
public void 회원수정(User user) {
    
    User persistance = userRepository.findById(user.getId()).orElseThrow(()->{
        return new IllegalArgumentException("회원 찾기 실패");
    });
    String rawPassword = user.getPassword(); //패스워드를 받아서 
    String encPassword = encoder.encode(rawPassword); //암호화
    persistance.setPassword(encPassword); //변경 된 패스워드를 암호화
    persistance.setEmail(user.getEmail()); // 변경 된 이메일
}

 

findById(user.getId()) 처럼 select해서 User오브젝트를 DB로부터 가져오는 이유는 영속화 하기 위해서이다.

 

수정시에는 영속성 컨텍스트 User 오브젝트를 영속화시키고 '영속화된 User오브젝트'를 수정한다. 
영속화 된 오브젝트를 변경하면 자동으로 DB에 update문을 날려준다.

 

 회원수정() 함수 종료시 = Service 종료 = 트랜잭션 종료 = commit 자동으로 된다.
 영속화 된 persistance 객체의 변화가 감지되면 더티체킹이 되어 자동으로 update문을 날려준다.

 

 

 

 

- 결과화면

비번과 이메일 변경시

 

DB에도 수정완료 

 

 

 

 

DB 값은 변경했으나 세션값은 변경이 안 돼있음

(로그아웃 하고 다시 로그인하면 값이 변경은 된다.)

 

 

 

 

세션값 변경은 다음 글에..

 

 

 

반응형
LIST

+ Recent posts