본문 바로가기
JAVA

Spring Boot 회원정보 출력 (1) 비동기 통신 Ajax

by fouink 2022. 9. 15.

 

 - index.html

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Team UP!</title>
  <style>
    pre{
      overflow: scroll;
    }
  </style>
</head>
</html>
<body>
  <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  <script type="text/javascript">
    console.log(sessionStorage.getItem("token"));
        $.ajax({
        contentType: "application/json",
        type: "GET",
        url: "/thymeleaf/getUsername",
        headers: {'Authorization':sessionStorage.getItem("token")},
        dataType: "json",
      }).done(function (res) {
          console.log("응답 성공");
          console.log(res.username);
          if (res.username !== null) {
            const loginMypage = document.getElementById("login/mypage");
            loginMypage.innerHTML = `<a href="/myPage" id="login/mypage">마이페이지</a>`;
            const joinLogout = document.getElementById("join/logout");
            joinLogout.innerHTML = `<a href="/logout" id="join/logout">로그아웃</a>`;
          }
        })
                .fail(function (res) {
                  console.log(res);
                });
  </script>

  <center><h2>TeamUP!</h2></center>
  <p><a>게시판</a></p> <hr/>
  <p><a href="/oauth2LoginPage">SNS 로그인</a></p> <hr/>
  <p><a id="login/mypage" href="/loginPage">일반 로그인</a></p> <hr/>
  <p><a id="join/logout" href="/joinPage">회원가입</a></p> <hr/>
</body>

인덱스 페이지에서 로그인 상태라면 html 의 id 태그 "login/mypage"부분과 "join/logout"부분이 ajax의 done부분으로 인해 바뀌게 된다 저게 가능한 이유는 인덱스 페이지를 읽을 때 ajax요청으로 서버에서 현재 로그인 된 사용자의 아이디 값을 찾아온다. 이 때 ajax의 dataType부분이 json이므로 json 으로 응답이 오지 않거나 done부분의 if문을 만족하지 않을 때는 실행하지 않고 그대로 밑의 html들을 읽는다.

 

 - 비로그인 상태

 

만약 회원이 로그인을 한 상태라면

이런식으로 렌더링이 된다.

 

여기서 마이페이지로 이동하게 되면

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>내 정보</title>
</head>
<body>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript">

        console.log(sessionStorage.getItem("token"));
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: "/thymeleaf/myPage",
            headers: {'Authorization':sessionStorage.getItem("token")},
            dataType: "json",
        }).done(function (res) {
            console.log("응답 성공");
            console.log(res);
            // if (res.username !== null) {
            //     const loginMypage = document.getElementById("login/mypage");
            //     loginMypage.innerHTML = `<a href="/myPage" id="login/mypage">마이페이지</a>`;
            //     const joinLogout = document.getElementById("join/logout");
            //     joinLogout.innerHTML = `<a href="/logout" id="join/logout">로그아웃</a>`;
            // }
            const inHtml = document.getElementById("username");
            var username = res.id;
            inHtml.innerHTML = username;
        })
            .fail(function (res) {
                console.log(res);
                alert("로그인 후 접근 가능한 페이지 입니다.");
                window.location.replace("/loginPage");
            });
    </script>
    <span id="username"></span>
<!--    <table border="1">-->
<!--        <tr>&lt;!&ndash; 첫번째 줄 시작 &ndash;&gt;-->
<!--            <td>첫번째 칸</td>-->
<!--            <td>두번째 칸</td>-->
<!--        </tr>&lt;!&ndash; 첫번째 줄 끝 &ndash;&gt;-->
<!--        <tr>&lt;!&ndash; 두번째 줄 시작 &ndash;&gt;-->
<!--            <td>첫번째 칸</td>-->
<!--            <td>두번째 칸</td>-->
<!--        </tr>&lt;!&ndash; 두번째 줄 끝 &ndash;&gt;-->
<!--    </table>-->


</body>
</html>

 

위 코드에 의해서 

이런식으로 회원 아이디가 출력이 된다

 

 - server Controller

@PostMapping("/thymeleaf/myPage")
@ResponseBody
public ResponseEntity<?> userInformation(
        Model model,
        @AuthenticationPrincipal PrincipalDetails principalDetails) {

    if (principalDetails != null) {
        UserInfo userInfo = principalDetails.getUserInfo();
        ResponseUserInfoDTO userInfoDTO = new ResponseUserInfoDTO();

        if (principalDetails.getUserInfo().getUsername().contains("naver")) {
            userInfoDTO.setID("NAVER 계정으로 로그인 중");
        } else if (principalDetails.getUserInfo().getUsername().contains("kakao")) {
            userInfoDTO.setID("KAKAO 계정으로 로그인 중");
        } else {
            userInfoDTO.setID(userInfo.getUsername());
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();

        cal.setTime(userInfo.getBirthday());

        // 하루 전
        cal.add(Calendar.DATE, +1);
        String birthday = dateFormat.format(cal.getTime());
        Date date = null;
        try {
            date = dateFormat.parse(birthday);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        userInfoDTO.setUser_birthday(date);
        userInfoDTO.setUser_email(userInfo.getEmail());
        userInfoDTO.setUser_gender(userInfo.getGender());
        userInfoDTO.setUser_phone(userInfo.getPhone());
        userInfoDTO.setUser_nickname(userInfo.getNickname());

        List<Map<String, Object>> teamList = teamService.getMyTeams(userInfo);

        if (teamList != null) {
            userInfoDTO.setTeam(teamList);
            return ResponseEntity.ok(userInfoDTO);
        } else {
            userInfoDTO.setTeam(null);
            return ResponseEntity.ok(userInfoDTO);
        }
    }else {
        return ResponseEntity.ok("bad");
    }

}

 

ajax의 dataType이 json이였으므로 bad가 온다면 로그인 페이지로 리턴을 하게 된다 

 

 

로그인 처리 및 콘솔에 찍어본 회원정보에 담긴 값 모두 html에 담는 포스팅은 시간이 나면 올려야될듯 하다..

댓글