public static User getCurrentUser() {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof User) {
return (User) principal;
}
}
或注射和铸造如下:
@RequestMapping(value = "/Foo/{id}",method = RequestMethod.GET)
public ModelAndView getFoo(@PathVariable Long id,Principal principal) {
User user = (User) ((Authentication) principal).getPrincipal();
..
最佳答案
我不认为它在春季3.2中有新的东西用于此目的.您是否考虑过使用自定义注释?
原文链接:https://www.f2er.com/spring/431478.html像这样的东西:
具有自定义注释的控制器:
@Controller
public class FooController {
@RequestMapping(value="/foo/bar",method=RequestMethod.GET)
public String fooAction(@LoggedUser User user) {
System.out.print.println(user.getName());
return "foo";
}
}
LoggedUser注释:
@Target(ElementType.PARAMETER)
@Retention(RententionPolicy.RUNTIME)
@Documented
public @interface LoggedUser {}
WebArgumentResolver:
public class LoggedUserWebArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter methodParameter,NativeWebRequest webRequest) {
Annotation[] annotations = methodParameter.getParameterAnnotations();
if (methodParameter.getParameterType().equals(User.class)) {
for (Annotation annotation : annotations) {
if (LoggedUser.class.isInstance(annotation)) {
Principal principal = webRequest.getUserPrincipal();
return (User)((Authentication) principal).getPrincipal();
}
}
}
return WebArgumentResolver.UNRESOLVED;
}
}
豆类配置: