Search
Duplicate

[스프링 게시판] 로그인 여부에 따른 버튼 표시

@3/20/2023

타임리프 enum 비교 문제

타임리프에서 enum 타입으로 비교를 하려면 아래처럼 패키지 명을 모두 써줘야 함
th:if="${day == T(my.package.MyEnum).MONDAY}"
Java
복사
하지만 이렇게 하면 리팩터링 시에 문제가 됨
.name()을 이용해 문자열 비교
약간 무식한 방법이지만 enum name 속성을 추출해서 비교하는 방법도 있음
th:if="${loginUser.role.name() == 'ADMIN'}"
Java
복사

로그인 여부에 따른 수정, 삭제 버튼

loginUser 속성은 아래처럼 LoginInterceptor에서 request attribute로 뷰에 넘겨주기 때문에 사용 가능함
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestURI = request.getRequestURI(); HttpSession session = request.getSession(false); if (session == null || session.getAttribute("loginUser") == null) { response.sendRedirect("/users/login?redirectURL=" + requestURI); return false; } else { User loginUser = (User) session.getAttribute("loginUser"); request.setAttribute("loginUser", loginUser); return true; } } }
Java
복사
게시글
<a th:if="${loginUser.id == post.user.id}" th:href="@{/posts/{postId}/edit(postId = ${post.id})}" class="col-md-6 col-sm-6 text-center fw-semibold">수정</a> <a th:if="${loginUser.id == post.user.id or loginUser.role.name() == 'ADMIN'}" th:href="@{/posts/{postId}/delete(postId = ${post.id})}" class="col-md-6 col-sm-6 text-center fw-semibold">삭제</a>
Java
복사
댓글 삭제 버튼
<button th:if="${commentListDTO.userId == loginUser.id}" th:onclick="|editComment(this, ${commentListDTO.commentId})|" class="col-6 btn btn-sm col-md-1 ms-md-auto text-center comment-button">수정 </button> <button th:if="${commentListDTO.userId == loginUser.id or loginUser.role.name() == 'ADMIN'}" th:classappend="${commentListDTO.userId != loginUser.id and loginUser.role.name() == 'ADMIN'} ? ms-auto : _" th:onclick="|location='@{/posts/{postId}/comments/{commentId}/delete (postId = ${post.id}, commentId = ${commentListDTO.commentId})}'|" class="col-6 btn btn-sm col-md-1 text-center comment-button">삭제 </button>
Java
복사