21. 회원수정하기v3

송민경's avatar
Mar 15, 2024
21. 회원수정하기v3

1. View 확인하기

notion image
{{> /layout/header}} <div class="container p-5"> <!-- 요청을 하면 localhost:8080/join POST로 요청됨 username=사용자입력값&password=사용자값&email=사용자입력값 --> <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" name="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" disabled> </div> <button type="submit" class="btn btn-primary form-control">회원가입수정</button> </form> </div> </div> </div> {{> /layout/footer}}
 

2. UserRepository 에 findById() 만들기

package shop.mtcoding.blog.user; import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import shop.mtcoding.blog.board.Board; @RequiredArgsConstructor @Repository public class UserRepository { private final EntityManager em; public User findById(int id) { User user = em.find(User.class, id); return user; } @Transactional public User save(User user){ em.persist(user); return user; } public User findByUsernameAndPassword(UserRequest.LoginDTO reqDTO){ Query query = em.createQuery("select u from User u where u.username = :username and u.password =:password", User.class); query.setParameter("username", reqDTO.getUsername()); query.setParameter("password", reqDTO.getPassword()); return (User) query.getSingleResult(); } }
 
  • 단위 테스트
package shop.mtcoding.blog.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.context.annotation.Import; import shop.mtcoding.blog.user.User; import shop.mtcoding.blog.user.UserRepository; import shop.mtcoding.blog.user.UserRequest; @Import(UserRepository.class) // IoC 등록코드 @DataJpaTest // Datasource(connection pool), EntityManager public class UserRepositoryTest { @Autowired // DI private UserRepository userRepository; @Test public void findById_test(){ // given int id = 1; // when userRepository.findById(id); // then System.out.println("findById_test : " + id); } @Test public void findByUsername_test(){ // given UserRequest.LoginDTO reqDTO = new UserRequest.LoginDTO(); reqDTO.setUsername("ssar"); reqDTO.setPassword("1234"); // when User user = userRepository.findByUsernameAndPassword(reqDTO); // then } }
notion image
 

3. UserController 에 updateForm 수정하기

  • session(mypage)에 있으니 URL에 id가 필요 없음
  • User 객체에서 필요한 것만 session에 담음 / User 객체의 모든 정보를 다 담지 않음
  • User 객체를 넣었기 때문에 동기화 해줘야함
  • session의 값이 변동되는 것이 아니라면 DB에 변경만 해주면 됨
package shop.mtcoding.blog.user; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @RequiredArgsConstructor @Controller public class UserController { private final UserRepository userRepository; private final HttpSession session; @PostMapping("/join") public String join(UserRequest.JoinDTO reqDTO) { User sessionUser = userRepository.save(reqDTO.toEntity()); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; } @PostMapping("/login") public String login(UserRequest.LoginDTO reqDTO) { User sessionUser = userRepository.findByUsernameAndPassword(reqDTO); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; } @GetMapping("/join-form") public String joinForm() { return "user/join-form"; } @GetMapping("/login-form") public String loginForm() { return "user/login-form"; } @GetMapping("/user/update-form") // session(mypage)에 있으니 id가 필요 없음 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"; } @GetMapping("/logout") public String logout() { session.invalidate(); return "redirect:/"; } }
 

4. view 수정해서 기존의 데이터 뿌리기

{{> /layout/header}} <div class="container p-5"> <!-- 요청을 하면 localhost:8080/join POST로 요청됨 username=사용자입력값&password=사용자값&email=사용자입력값 --> <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" value="{{user.username}}" class="form-control" placeholder="Enter username" name="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" value="{{user.email}}" class="form-control" placeholder="Enter email" name="email" disabled> </div> <button type="submit" class="btn btn-primary form-control">회원가입수정</button> </form> </div> </div> </div> {{> /layout/footer}}
notion image
notion image
  • 수정할 값만 name값이 있으면 됨
{{> /layout/header}} <div class="container p-5"> <!-- 요청을 하면 localhost:8080/join POST로 요청됨 username=사용자입력값&password=사용자값&email=사용자입력값 --> <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" value="{{user.username}}" 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 type="email" value="{{user.email}}" class="form-control" placeholder="Enter email" disabled> </div> <button type="submit" class="btn btn-primary form-control">회원가입수정</button> </form> </div> </div> </div> {{> /layout/footer}}
notion image
 

5. password와 emil 수정하게 변경하기

  • 변경될 값에 name값이 없으면 no key라 에러가 남!!
{{> /layout/header}} <div class="container p-5"> <!-- 요청을 하면 localhost:8080/join POST로 요청됨 username=사용자입력값&password=사용자값&email=사용자입력값 --> <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" value="{{sessionUser.username}}" 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 type="email" value="{{sessionUser.email}}" class="form-control" placeholder="Enter email" name="email"> </div> <button type="submit" class="btn btn-primary form-control">회원가입수정</button> </form> </div> </div> </div> {{> /layout/footer}}
 

6. UserRepository 에서 updateById 만들기

package shop.mtcoding.blog.user; import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import shop.mtcoding.blog.board.Board; @RequiredArgsConstructor @Repository public class UserRepository { private final EntityManager em; @Transactional public User updateById(int id, String password, String email) { // DTO를 안만들고 꺼내서 넘겨도 됨 -> 재사용 가능 User user = findById(id); user.setPassword(password); user.setEmail(email); return user; } // 더티체킹 public User findById(int id) { // 연관된 객체가 없음 -> 연관된 객체가 있으면 테스트 필요 User user = em.find(User.class, id); return user; } @Transactional public User save(User user){ em.persist(user); return user; } public User findByUsernameAndPassword(UserRequest.LoginDTO reqDTO){ Query query = em.createQuery("select u from User u where u.username = :username and u.password =:password", User.class); query.setParameter("username", reqDTO.getUsername()); query.setParameter("password", reqDTO.getPassword()); return (User) query.getSingleResult(); } }
 
  • 단위 테스트하기
package shop.mtcoding.blog.User; import jakarta.persistence.EntityManager; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.context.annotation.Import; import shop.mtcoding.blog.user.User; import shop.mtcoding.blog.user.UserRepository; import shop.mtcoding.blog.user.UserRequest; @Import(UserRepository.class) // IoC 등록코드 @DataJpaTest // Datasource(connection pool), EntityManager public class UserRepositoryTest { @Autowired // DI private UserRepository userRepository; @Autowired private EntityManager em; @Test public void updateById_test(){ // given int id = 1; String password="123456"; String email = "ssar12@naver.com"; // when userRepository.updateById(id, password, email); // then em.flush(); System.out.println("updateById_test : " + id); System.out.println("updateById_test : " + password); System.out.println("updateById_test : " + email); } @Test public void findById_test(){ // given int id = 1; // when userRepository.findById(id); // then System.out.println("findById_test : " + id); } @Test public void findByUsername_test(){ // given UserRequest.LoginDTO reqDTO = new UserRequest.LoginDTO(); reqDTO.setUsername("ssar"); reqDTO.setPassword("1234"); // when User user = userRepository.findByUsernameAndPassword(reqDTO); // then } }
notion image
 

7. UserController 에서 update 만들기

  • URL에 ID가 없으므로 session에서 ID 가져오기
  • DTO에서 값을 받아 update 쿼리 실행하기
  • sessionUser 변수 만들어 mustach에 적용하기
package shop.mtcoding.blog.user; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @RequiredArgsConstructor @Controller public class UserController { private final UserRepository userRepository; private final HttpSession session; @PostMapping("/user/update") public String update(UserRequest.UpdateDTO reqDTO){ User sessionUser = (User) session.getAttribute("sessionUser"); User newSessionUser = userRepository.updateById(sessionUser.getId(), reqDTO.getPassword(), reqDTO.getEmail()); session.setAttribute("sessionUser", newSessionUser); System.out.println(sessionUser); return "redirect:/"; } @PostMapping("/join") public String join(UserRequest.JoinDTO reqDTO) { User sessionUser = userRepository.save(reqDTO.toEntity()); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; } @PostMapping("/login") public String login(UserRequest.LoginDTO reqDTO) { User sessionUser = userRepository.findByUsernameAndPassword(reqDTO); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; } @GetMapping("/join-form") public String joinForm() { return "user/join-form"; } @GetMapping("/login-form") public String loginForm() { return "user/login-form"; } @GetMapping("/user/update-form") // session(mypage)에 있으니 id가 필요 없음 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"; } @GetMapping("/logout") public String logout() { session.invalidate(); return "redirect:/"; } }
notion image
notion image
notion image
 
Share article

vosw1