[자바 스프링부트] 회원정보 수정 ajax (3차 프로젝트 WORLD )

Glen(OH TaekJoo)·2023년 8월 9일
0

Study

목록 보기
35/53
post-thumbnail

마이페이지에서 회원정보를 수정하려고 한다.

요구사항

  • 유저 entity 상 닉네임은 unique 로 되어있어 같은닉네임으로 변경이 불가능하다
  • 비밀번호는 빈값으로 제출이 불가능하다
  • 비밀번호 확인은 위에 작성한 비밀번호와 동일해야한다
  • 빈칸을 모두 입력해야 수정이 가능하다

기존 Html, 컨트롤러 코드

@PostMapping("/user/modify")
    @PreAuthorize("isAuthenticated()")
    public String userEdit(UserForm userForm, Principal principal, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return "redirect:/mypage/user";
        }else if (!userForm.getPassword1().equals(userForm.getPassword2())) {
            bindingResult.rejectValue("password2", "비밀번호 2개가 일치하지 않습니다.");
            return "redirect:/mypage/user";
        }else {
        SiteUser siteUser = this.userService.getUser(principal.getName());
        this.userService.modifyUser(siteUser,userForm.getNickname(),userForm.getPassword1());
        return "redirect:/mypage/user";
        }
    }
<form  class="usrmodify" th:action="@{/mypage/user/modify}" th:object="${userForm}" method="post">
        <div>
          <span>USER ID :</span>
          <span class="usremail" th:text='${user.username}'></span>
        </div>
        <div>
          <span>New NickName : </span>
          <input type="text" th:placeholder="${user.nickname}" th:defaultValue="${user.nickname}" th:field="*{nickname}">
        </div>
        <div>
          <span>New PW : </span>
          <input type="password" th:field="*{password1}">
        </div>
        <div>
          <span>Re-New Pw : </span>
          <input type="password" th:field="*{password2}">
        </div>
        <div>
          <button type="submit" id="submitButton">Reset</button>
        </div>
      </form>

기존에는 postmapping 을 이용하여 수정을 하고 리턴값으로 페이지가 리로드 되게 하였다.
에러가 있을경우도 페이지가 리로드되었다.

수정한 코드

@PostMapping("/user/modify")
    @PreAuthorize("isAuthenticated()")
    @ResponseBody
    public String userEdit(UserForm userForm, Principal principal, BindingResult bindingResult) {
        SiteUser siteUser = this.userService.getUser(principal.getName());
        if (bindingResult.hasErrors()) {
            return "다시 시도해 주세요. ";
        }else if (userForm.getPassword1().equals("")) {
            return "변경할 비밀번호를 입력해주세요";
        }else if (userForm.getNickname().equals("")) {
            return "변경할 닉네임을 입력해주세요";
        }else if (!userForm.getPassword1().equals(userForm.getPassword2())) {
            return "비밀번호 2개가 일치하지 않습니다.";
        }else if (userForm.getNickname().equals(siteUser.getNickname())) {
            return "같은 닉네임으로는 변경이 불가능합니다.";
        }else {
            this.userService.modifyUser(siteUser,userForm.getNickname(),userForm.getPassword1());
            return "성공적으로 수정되었습니다.";
        }
    }

컨트롤러쪽은 예외처리를 추가하였으며 동작 메세지를 ResponseBody 로 리턴했다.

$(document).ready(function() {
    $(".usrmodify").submit(function(event) {
        event.preventDefault(); // 폼 제출 방지

        $.ajax({
            type: "POST",
            url: $(this).attr("action"),
            data: $(this).serialize(),
            success: function(response) {
                alert(response); // 서버에서 반환된 메시지를 alert로 표시
                if (response === "성공적으로 수정되었습니다.") {
                    location.reload(); // 페이지 리로드
                }
            },
            error: function(xhr, status, error) {
                alert("오류가 발생했습니다. 다시 시도해주세요.");
            }
        });
    });
});

폼제출 동작에 event를 걸어 폼제출을 방지하고
ajax 로 해당값을 제출하고 받아왔다.
받아온값은 alert 로 새창을 띄워 오류메시지를 확인할 수 있게 하였다.
또한 리턴값이 "성공적으로 수정되었습니다." 라면 해당 페이지를 리로드 되게 설정했다.

완료페이지

이제 해당 수정란에서 오류메시지와 성공메시지를 새창으로 확인할 수 있다.

profile
병아리 개발자 의 우당탕탕 성장기

0개의 댓글