SessionInterceptor.java 901 B

12345678910111213141516171819202122232425
  1. package org.example.sweater.controller;
  2. import jakarta.servlet.http.HttpServletRequest;
  3. import jakarta.servlet.http.HttpServletResponse;
  4. import org.example.sweater.domain.User;
  5. import org.springframework.security.core.Authentication;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.web.servlet.HandlerInterceptor;
  8. import java.security.Principal;
  9. @Component
  10. public class SessionInterceptor implements HandlerInterceptor {
  11. @Override
  12. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  13. Principal principal = request.getUserPrincipal();
  14. if (principal != null) {
  15. Authentication authentication = (Authentication) principal;
  16. User user = (User) authentication.getPrincipal();
  17. request.setAttribute("user", user);
  18. }
  19. return true;
  20. }
  21. }