이거 한 번 해보자!!
지금은 password만 수정할 수 있는데, password와 email 2개를 수정할 수 있게 바꿔주자.
[ 내 코드 ]
UserRepository
@RequiredArgsConstructor @Repository public class UserRepository { private final EntityManager em; @Transactional public User update(int sessionId, UserRequest.UpdateDTO requestDTO) { User user = findById(sessionId); user.update(requestDTO); return user; } public User findById(int id) { User user = em.find(User.class, id); return user; }
UserController
@RequiredArgsConstructor @Controller public class UserController { private final UserRepository userRepository; private final HttpSession session; @PostMapping("/user/update") public String update(UserRequest.UpdateDTO requestDTO) { User sessionUser = (User) session.getAttribute("sessionUser"); userRepository.update(sessionUser.getId(), requestDTO); return "redirect:/"; } @GetMapping("/user/update-form") public String updateForm(HttpServletRequest request) { User sessionUser = (User) session.getAttribute("sessionUser"); //id는 세션에서 들고오자! User user = userRepository.findById(sessionUser.getId()); request.setAttribute("user", user); return "user/update-form"; }
근데 이거 아까 말했듯이 sessionUser에서 바로 빼오지 말고, 조회해서 빼오라고 했던 것 같음 …
User
package shop.mtcoding.blog.user; import jakarta.persistence.*; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import java.sql.Timestamp; @NoArgsConstructor @Data @Table(name = "user_tb") @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true) private String username; private String password; private String email; @CreationTimestamp // pc -> db (날짜주입) private Timestamp createdAt; @Builder public User(Integer id, String username, String password, String email, Timestamp createdAt) { this.id = id; this.username = username; this.password = password; this.email = email; this.createdAt = createdAt; } public void update(UserRequest.UpdateDTO requestDTO) { this.password = requestDTO.getPassword(); this.email = requestDTO.getEmail(); } }
[ user/update-form.mustache ]
<form action="/user/update" method="post" enctype="application/x-www-form-urlencoded"> <div class="mb-3"> <input value="{{user.username}}" type="text" class="form-control" placeholder="Enter username" disabled> </div> <div class="mb-3"> <input type="password" class="form-control" placeholder="Enter password" name="password"> </div> <div class="mb-3"> <input value="{{user.email}}" type="email" class="form-control" placeholder="Enter email" name="email"> </div> <button type="submit" class="btn btn-primary form-control">회원가입수정</button> </form>
[ 화면 확인 ]
[ DB 확인 ]
바뀌었음!
Share article