Nim*_*sky 5 java spring spring-mvc
我想访问当前登录的用户,我这样做(从静态方法)
public static User getCurrentUser() {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof User) {
return (User) principal;
}
}
Run Code Online (Sandbox Code Playgroud)
或注射和铸造如下:
@RequestMapping(value = "/Foo/{id}", method = RequestMethod.GET)
public ModelAndView getFoo(@PathVariable Long id, Principal principal) {
User user = (User) ((Authentication) principal).getPrincipal();
..
Run Code Online (Sandbox Code Playgroud)
在用户实现用户细节的地方,两者看起来有点蹩脚在Spring 3.2中有更好的方法吗?
我不认为它spring 3.2为此目的有什么新东西。您是否考虑过使用自定义注释?
像这样的东西:
带有自定义注释的控制器:
@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";
}
}
Run Code Online (Sandbox Code Playgroud)
LoggedUser 注释:
@Target(ElementType.PARAMETER)
@Retention(RententionPolicy.RUNTIME)
@Documented
public @interface LoggedUser {}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
豆配置:
<bean id="loggedUserResolver" class="com.package.LoggedUserWebArgumentResolver" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="loggedUserResolver" />
</bean>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
993 次 |
| 最近记录: |