@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}
public class SessionUser implements Serializable {
private String name;
private String email;
private String picture;
...
}
HandlerMethodArgumentResolver를 상속받은 CustomHandlerMethodArgumentResolver을 작성해줍니다.
HandlerMethodArgumentResolver를 상속받은 객체는 아래 두개의 메소드를 구현해야 합니다.
boolean supportsParameter(MethodParameter parameter);
Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory);
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {
private final HttpSession httpSession;
@Override
public boolean supportsParameter(MethodParameter parameter) {
boolean isLoginUserAnnotation = parameter.getParameterAnnotation(LoginUser.class) != null;
boolean isUserClass = SessionUser.class.equals(parameter.getParameterType());
return isLoginUserAnnotation && isUserClass;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return httpSession.getAttribute("user");
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private CustomHandlerMethodArgumentResolver customHandlerMethodArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(customHandlerMethodArgumentResolver);
}
}
public String index(Model model, @LoginUser SessionUser user);