62. 회원수정1
by 볼빵빵오춘기UserContrller
@GetMapping("/user/updateForm") public String updateForm(){ return "user/updateForm"; }
updateForm.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8 " pageEncoding="UTF-8"%> <%@ include file="../layout/header.jsp"%> <div class="container"> <h2>Stacked form</h2> <form> <input type="hidden" id="id" value="${principal.user.id}"> <input type="hidden" id="username" value="${principal.user.username}"> <div class="form-group"> <label for="username">username:</label> <input type="text" value="${principal.user.username}" class="form-control" id="username" placeholder="Enter username" name="username" readonly> </div> <c:if test="${empty principal.user.oauth}"> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" id="password" placeholder="Enter password" name="password"> </div> </c:if> <div class="form-group"> <label for="email">Email:</label> <input type="email" value="${principal.user.email}" class="form-control" id="email" placeholder="Enter email" name="email"> </div> </form> <button id="btn-update" class="btn btn-primary">정보 수정완료</button> </div> <script src="/js/user.js"></script> <%@ include file="../layout/footer.jsp"%>
user.js
$("#btn-update").on("click",()=>{ // function(){} 대신 ()=> 사용한 이유는 this를 바인딩하기 위해서 this.update(); });
update: function(){ let data = { id: $("#id").val(), username: $("#username").val(), password: $("#password").val(), email: $("#email").val() } $.ajax({ type: "PUT", url: "/user", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json" }).done(function(resp){ // alert(resp); alert("회원수정이 완료 되었습니다.") location.href="/"; }).fail(function(error){ alert(JSON.stringify(error)); }); },// update end
UserApiController
@PutMapping("/user") public ResponseDto<Integer> update(@RequestBody User user) { userService.회원수정(user); return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);//자바오브젝트를 JSON으로 변환해서 리턴 }
UserService
@Autowired private BCryptPasswordEncoder encoder;
@Transactional public void 회원수정(User user) { // 수정시에는 영속성 컨텍스트 User 오브젝트를 영속화시키고, 영속화된 User 오브젝트를 수정 // select를 해서 User 오브젝트를 DB로 부터 가져오는 이유는 영속화를 하기 위해서 // 영속화된 오브젝트를 변경하면 자동으로 DB에 Update문을 날려준다. User persistance = userRepository.findById(user.getId()).orElseThrow(()->{ return new IllegalArgumentException("회원 찾기 실패"); }); // Validate 체크 => oauth 필드에 값이 없으면 수정 가능 if(persistance.getOauth() == null || persistance.getOauth().equals("")){ String rawPassword = user.getPassword(); String encPassword = encoder.encode(rawPassword); persistance.setPassword(encPassword); persistance.setEmail(user.getEmail()); } // 회원 수정 삼수 종료 시 = 서비스 종료 시 = 트랜잭션 종료 = commit이 자동으로 된다. // commit이 자동으로 되면 영속화된 persistance 객체의 변화가 감지되면 // 더티체킹이 되어 update문을 날려준다. }

블로그의 정보
Hello 춘기's world
볼빵빵오춘기활동하기
Hello 춘기's world볼빵빵오춘기 님의 블로그입니다.