Spring
[타임리프] Session Id를 html, js에 가져다 쓰는 방법
Lea Hwang
2023. 2. 8. 01:01
토이프로젝트를 할 때 html이나 js로 sessionId가 넘어가지 않아서 애를 많이 먹었습니다. 오히려 자바 코드 짜는 것보다 이 부분에서 시간을 더 많이 쏟은 듯합니다. 그만큼 헷갈리고 다음에도 헷갈릴 가능성이 있기에 기록으로 남겨둡니다.
html
Controller
@GetMapping("/user/{pageUserId}")
public String profile(@PathVariable int pageUserId, Model model, @AuthenticationPrincipal CustomUserDetails customUserDetails) {
...
model.addAttribute("sessionId", customUserDetails.getUser().getId());
return "/user/profile";
}
이렇게 하면 header에서도 사용할 수 있습니다.
profile.html
<button th:onclick="'profileImageUpload(' + ${dto.user.id} + ', ' + ${principalId} + ')'">사진 업로드</button>
js
Controller
@GetMapping({"/","/image/story"})
public String story(@AuthenticationPrincipal CustomUserDetails customUserDetails, Model model) {
model.addAttribute("sessionId", customUserDetails.getUser().getId());
return "/image/story";
}
story.html
<script>
let sessionId = [[ ${sessionId} ]]
</script>
story.js
if(sessionId == comment.user.id) {
item += `<button>
<i class="fas fa-times"></i>
</button>`;
}