Q&A
前提
Springを個人開発をしています。
ユーザーがログインしている間、ログインしているユーザーのアイコンを画面に表示したいと考えています。
しかし、画像をうまく表示できませんでした。
実現したいこと
- ログインしているユーザーの画像を表示する
該当のソースコード
一画面だけでなく各画面を跨いで使用したいため、HTTPリクエスト毎にSQLを発行しパスを取得するのではなく、ログインの段階で一括で取得し、後はその情報を保持するようしたいです。
java
1package com.example.service.impl; 2 3import org.springframework.beans.factory.annotation.Autowired; 4import org.springframework.security.core.authority.AuthorityUtils; 5import org.springframework.security.core.userdetails.User; 6import org.springframework.security.core.userdetails.UserDetails; 7import org.springframework.security.core.userdetails.UserDetailsService; 8import org.springframework.security.core.userdetails.UsernameNotFoundException; 9import org.springframework.stereotype.Service; 10 11import com.example.model.MUser; 12import com.example.service.UserService; 13 14import jakarta.servlet.http.HttpSession; 15import lombok.extern.slf4j.Slf4j; 16 17@Service 18public class UserDetailsServiceImpl implements UserDetailsService { 19 20 @Autowired 21 private UserService service; 22 23 @Autowired 24 private HttpSession session; 25 26 @Override 27 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 28 29 // ユーザー情報取得 30 MUser loginUser = service.getLoginUser(username); 31 32 // ユーザーが存在しない場合 33 if(loginUser == null) { 34 throw new UsernameNotFoundException(username + "not found"); 35 } 36 37 session.setAttribute("loginUserIcon", loginUser.getAccountIcon2()); 38 39 // ユーザー情報を返す 40 return new User(loginUser.getUserId(), loginUser.getPassword(), 41 AuthorityUtils.createAuthorityList(loginUser.getAuthority().name())); 42 } 43}
html
1 <li class="nav-item"> 2 <a class="nav-link"> 3 <img th:src="${loginUserIcon}" alt="アイコン画像" th:width="50px" th:height="50px"> 4 </a> 5 </li>
試したこと
Spring SecurityのUserDetalServiceを実装し、ユーザーを認証するタイミングでsessionスコープを用いて画像のパス(loginUser.getAccountIcon2())を取得しようと考えています。
補足情報(FW/ツールのバージョンなど)
Spring Boot 3.0.1
JRE 17