1. View 확인
데이터를 받기 위해 DTO 를 만든다.
@Data public static class UpdateDTO{ private String password; private String email; }
2. 레파지토리
@Transactional public User updateById(int id,UserRequest.UpdateDTO requestDTO){ User user = findById(id); user.setPassword(requestDTO.getPassword()); user.setEmail(requestDTO.getEmail()); return user; }
3. 컨트롤러
@GetMapping("/user/update-form") public String updateForm(HttpServletRequest request) { User sessionUser = (User) session.getAttribute("sessionUser"); //수정 페이지에 기존 데이터 들고 User user = userRepository.findById(sessionUser.getId()); request.setAttribute("user",user); return "user/update-form"; } @PostMapping("/user/update") public String update(UserRequest.UpdateDTO requestDTO){ User sessionUser = (User) session.getAttribute("sessionUser"); User user = userRepository.updateById(sessionUser.getId(),requestDTO); //세션에 업데이트값 동기화 session.setAttribute("sessionUser",user); return "redirect:/"; }
user 데이터를 업데이트 후 세션에 다시 덮어씌운다.
4. View
<div class="card"> <div class="card-header"><b>회원수정을 해주세요</b></div> <div class="card-body"> <form action="/user/update" method="post" enctype="application/x-www-form-urlencoded"> <div class="mb-3"> <input type="text" class="form-control" placeholder="Enter username" value="{{user.username}}" disabled> </div> <div class="mb-3"> <input type="password" class="form-control" placeholder="Enter password" name="password"> </div> <div class="mb-3"> <input type="email" class="form-control" placeholder="Enter email" name="email" value="{{user.email}}"> </div> <button type="submit" class="btn btn-primary form-control">회원가입수정</button> </form>
Share article