Post

HOME

JSP로 view를 만들려고 한다.

컨트롤러

1
2
3
4
5
@GetMapping("/home")
    public String home() {
        return "home";
    }

/home으로 이동하면 hoem.jsp로 이동한다.

홈화면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> //jstl에서 사용하는 태그를 사용하기 위해서 선언
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>🛒 TechComputeMall</title>
</head>
<body>
<%@ include file="/WEB-INF/views/menu.jsp" %>
<div style="text-align:center">
    <img src="static/images/computer.png" alt="computer1">

<h1>WELCOME</h1>

</div>
</div>
</body>
</html>

메뉴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>🛒 TechComputeMall</title>
    <link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css"/>
</head>
<body>
<div id="menu">
    <ul>
        <li id="logo"><a href="<c:url value='/home'/>">TechComputeMall</a></li>
        <li><a href="<c:url value='/item/itemsPage'/>">상품보러가기</a></li>
        <li id="login-logout">
            <a href="/loginForm" onclick="toggleLoginStatus()">
                <span id="login-text"></span>
            </a>
            <span id="user-name" style="display: none;" >
                <span id="user-name-value"></span>
            </span>
        </li>
        <li id="admin" style="display: none;">
            <a href="/itemUpload">관리자페이지</a>
        </li>
        <li><a href=""><i class="fa fa-search"></i></a></li>
    </ul>
</div>



<script>

    // access_token 값을 가져오기
    const access_token = localStorage.getItem('access_token');
    console.log("access_token= " + access_token);

    // 토큰이 있다면 디코딩
    if (access_token) {
        const decodedToken = parseJwt(access_token);

        // 클레임에서 원하는 정보 추출
        const username = decodedToken.name;
        const role = decodedToken.roles;
        console.log('사용자 이름:', username);
        console.log('역할',role)


        //  사용자 이름이 있을 때만 보이도록 변경
        if (username) {
            document.getElementById('login-text').innerText = '로그아웃';
            document.getElementById('user-name').style.display = 'inline';
            document.getElementById('user-name-value').innerText = username;
            //  사용자가 admin일 때만 상품등록하기 메뉴 표시
            if (role.includes('ADMIN')) {
                document.getElementById('admin').style.display = 'inline';
            }
        }
    } else {
        console.log('토큰이 없습니다.');
        document.getElementById('login-text').innerText = '로그인';

    }

    // JWT 토큰 디코딩 함수
    function parseJwt(token) {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        return JSON.parse(jsonPayload);
    }


    //  로그인/로그아웃 토글 함수
    function toggleLoginStatus() {
        if (access_token) {
            localStorage.removeItem('access_token');
            console.log('로그아웃');
        } else {
            //
            console.log('로그인');
        }

        // 페이지 리로딩
        location.reload();
    }
</script>

</body>
</html>

script를 사용해서 자바스크립트를 선언해주었다.

로그인했을때 localStorage에 토큰을 저장해두었다.

토큰을 가져와서 디코딩을 한뒤 토큰에 저장해두었던 이름과 역할을 추출하였다.

그래서 role이 admin이 아닐때 관리자 페이지가 안보이게 숨겨두었다.

로그인이 성공적으로 이루어지면 토큰에서 이름을 추출해서 보일 수 있게 해두었다.

localStorage에 accessToken이 없을 때는 로그인이 보이게

있을때는 localStorage.removeItem(‘access_token’)를 사용해서 로그아웃이 가능하게 했다.

image

image

This post is licensed under CC BY 4.0 by the author.