java – 访问服务层和控制器中的spring用户 – Spring 3.2的任何更新?

前端之家收集整理的这篇文章主要介绍了java – 访问服务层和控制器中的spring用户 – Spring 3.2的任何更新?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想访问当前登录用户,我这样做(从静态方法)

  1. public static User getCurrentUser() {
  2. final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  3. if (principal instanceof User) {
  4. return (User) principal;
  5. }
  6. }

或注射和铸造如下:

  1. @RequestMapping(value = "/Foo/{id}",method = RequestMethod.GET)
  2. public ModelAndView getFoo(@PathVariable Long id,Principal principal) {
  3. User user = (User) ((Authentication) principal).getPrincipal();
  4. ..

用户实现用户细节的地方,两者看起来有点蹩脚在Spring 3.2中有更好的方法吗?

最佳答案
我不认为它在春季3.2中有新的东西用于此目的.您是否考虑过使用自定义注释?

像这样的东西:

具有自定义注释的控制器:

  1. @Controller
  2. public class FooController {
  3. @RequestMapping(value="/foo/bar",method=RequestMethod.GET)
  4. public String fooAction(@LoggedUser User user) {
  5. System.out.print.println(user.getName());
  6. return "foo";
  7. }
  8. }

LoggedUser注释:

  1. @Target(ElementType.PARAMETER)
  2. @Retention(RententionPolicy.RUNTIME)
  3. @Documented
  4. public @interface LoggedUser {}

WebArgumentResolver:

  1. public class LoggedUserWebArgumentResolver implements WebArgumentResolver {
  2. public Object resolveArgument(MethodParameter methodParameter,NativeWebRequest webRequest) {
  3. Annotation[] annotations = methodParameter.getParameterAnnotations();
  4. if (methodParameter.getParameterType().equals(User.class)) {
  5. for (Annotation annotation : annotations) {
  6. if (LoggedUser.class.isInstance(annotation)) {
  7. Principal principal = webRequest.getUserPrincipal();
  8. return (User)((Authentication) principal).getPrincipal();
  9. }
  10. }
  11. }
  12. return WebArgumentResolver.UNRESOLVED;
  13. }
  14. }

豆类配置:

猜你在找的Spring相关文章