从Spring3.1开始有了HandlerMethodArgumentResolver接口,可以为@RequestMapping标注的方法扩展其传入参数。
首先,自定义注解CurrentUser
- @Target({ElementType.PARAMETER})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface CurrentUser {
-
- /**
- * 当前用户在request中的名字 默认user
- *
- * @return
- */
- String value() default "user";
- }
然后,实现HandlerMethodArgumentResolver接口
- import org.springframework.core.MethodParameter;
- import org.springframework.web.bind.support.WebDataBinderFactory;
- import org.springframework.web.context.request.NativeWebRequest;
- import org.springframework.web.method.support.HandlerMethodArgumentResolver;
- import org.springframework.web.method.support.ModelAndViewContainer;
-
- public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
-
- public CurrentUserMethodArgumentResolver() {
- }
-
- @Override
- public boolean supportsParameter(MethodParameter parameter) {
- if (parameter.hasParameterAnnotation(CurrentUser.class)) {
- return true;
- }
- return false;
- }
-
- @Override
- public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
- CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);
- return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_REQUEST);
- }
- }
在Spring-MVC的配置文件中加入以下配置:
- <mvc:annotation-driven>
- <mvc:argument-resolvers>
- <bean class="xx.xx.xx.CurrentUserMethodArgumentResolver" />
- </mvc:argument-resolvers>
- </mvc:annotation-driven>
这样,你就可以在有@RequestMapping标注的的方法中使用了,如
- @RequestMapping(value = "index")
- public String index(@CurrentUser User user, Model model) {
- System.out.println(user.getUsername());
- return "admin/index";
- }