<div class="subscribe">
<ul>
<li><a href=""> 게시물<span>${user.images.size()}</span>
</a></li>
<li><a href="javascript:subscribeInfoModalOpen();"> 구독정보<span>2</span>
</a></li>
</ul>
El표현식 사용으로 user.images.size를 해주면 간단하게 총 게시물을 띄울 수 있다.
이제는 타인의 게시물도 볼수있도록 뷰 렌더링을 한다.
내 페이지에서는 구독하기 버튼이 나오지않도록 지정하고,
내가 타인의 페이지로 들어간다고 가정하자,
그렇다면 타인이 올린 사진이 보여야 할것이고, 사진등록 버튼 역시 보이면 안됀다.
(구독하기는 아직 미구현)
방법에는 2가지 방법이 있는데
1. JSP EL태그 사용하기
<c:choose>
<c:when test="${principal.user.id == user.id}">
<button class="cta" onclick="location.href='/image/upload'">사진등록</button>
</c:when>
<c:otherwise>
<button class="cta" onclick="toggleSubscribe(this)">구독하기</button>
</c:otherwise>
</c:choose>
JSP 의 EL태그를 사용해서 PrincipalDetail 의 로그인정보와, user의 id정보를 통해서 만드는 방법이 있고
2. DTO 사용하기(만들어서 VIEW로 가져옴)
UserProfileDto
import com.pyo.yourspick.domain.user.User;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserProfileDto {
private boolean pageOwnerState;
private User user;
private int imageCount;
}
UserController
@GetMapping("user/{pageUserId}")
public String profile(@PathVariable int pageUserId, Model model,@AuthenticationPrincipal PrincipalDetails principalDetails){
UserProfileDto dto = userService.회원프로필(pageUserId,principalDetails.getUser().getId());
model.addAttribute("dto", dto);
return "user/profile";
}
UserService
@Transactional(readOnly = true)
public UserProfileDto 회원프로필(int pageUserId, int principalId){
UserProfileDto dto = new UserProfileDto();
User userEntity = userRepository.findById(pageUserId).orElseThrow(() ->{
throw new CustomException("해당 유저 프로필 페이지는 찾을 수 없습니다.");
});
dto.setUser(userEntity);
dto.setPageOwnerState(pageUserId == principalId);
dto.setImageCount(userEntity.getImages().size());
return dto;
}
}
이런식으로 dto에서 처리를 해주는 것도 가능하다.
<c:choose>
<c:when test="${dto.pageOwnerState}">
<button class="cta" onclick="location.href='/image/upload'">사진등록</button>
</c:when>
<c:otherwise>
<button class="cta" onclick="toggleSubscribe(this)">구독하기</button>
</c:otherwise>
</c:choose>
세션의 이름이 dto로 변경되었으므로 el태그의 이름도 바꿔주면 끝.
Q. 누가봐도 1번이 쉬운데 왜 2번의 방법으로 하는지?
A. view단에서 자바 코드를 이용한 연산이 일어나는건 좋은상황이 아님(현업에서는 프론트와 백엔드가 구분되어있으므로) 최대한 백엔드에서 연산을 처리하고 view단으로 넘어가는 습관을 가지자.
'Spring > JPA + Security' 카테고리의 다른 글
[Spring Data JPA] 로그인 상태에 따라 다른 구독버튼 / 구독하기 - 1-1 (0) | 2023.01.10 |
---|---|
[Spring Data JPA] 구독하기 구현하기 - 1 구독 정보 DB 완성 및 구현 (0) | 2023.01.10 |
[Spring Data JPA] 게시판 띄우는 로직 만들기 1-1 무한 참조 오류 (0) | 2023.01.10 |
[Spring Data JPA] 게시판 띄우는 로직 만들기 - 1 양방향 맵핑 및 이미지 뷰 렌더링 (0) | 2023.01.10 |
[Spring Data JPA] JPA를 사용한 이미지 업로드 (0) | 2023.01.08 |
댓글