CurrentUserMethodArgumentResolver.java 1.5 KB

12345678910111213141516171819202122232425262728293031
  1. package com.jkcredit.invoice.annotation.annotationDes;
  2. import com.jkcredit.invoice.annotation.CurrentUser;
  3. import com.jkcredit.invoice.model.entity.user.User;
  4. import org.springframework.core.MethodParameter;
  5. import org.springframework.web.bind.support.WebDataBinderFactory;
  6. import org.springframework.web.context.request.NativeWebRequest;
  7. import org.springframework.web.context.request.RequestAttributes;
  8. import org.springframework.web.method.support.HandlerMethodArgumentResolver;
  9. import org.springframework.web.method.support.ModelAndViewContainer;
  10. import org.springframework.web.multipart.support.MissingServletRequestPartException;
  11. /**
  12. * 增加方法注入,将含有 @CurrentUser 注解的方法参数注入当前登录用户
  13. */
  14. public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
  15. @Override
  16. public boolean supportsParameter(MethodParameter parameter) {
  17. return parameter.getParameterType().isAssignableFrom(User.class)
  18. && parameter.hasParameterAnnotation(CurrentUser.class);
  19. }
  20. @Override
  21. public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
  22. User user = (User) webRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST);
  23. if (user != null) {
  24. return user;
  25. }
  26. throw new MissingServletRequestPartException("currentUser");
  27. }
  28. }