本文介绍了春天HandlerMethodArgumentResolver不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring MVC的3.2.2

I am using Spring MVC 3.2.2

我已经定义了一个自定义HandlerMethodArgumentResolver类像这样

I have defined a custom HandlerMethodArgumentResolver class like this

public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

  public CurrentUserArgumentResolver() {
    System.out.println("Ready");
  }

  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return parameter.hasParameterAnnotation(CurrentUser.class);
  }

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

      Principal principal = webRequest.getUserPrincipal();
      System.out.println("*** Principal ***: " + principal);
      return principal;
  }
}

并添加以下到我的应用程序-servlet.xml中

And added the following to my app-servlet.xml

<mvc:annotation-driven>
  <mvc:argument-resolvers>
    <beans:bean class="my.package.CurrentUserArgumentResolver" lazy-init="false"/>
  </mvc:argument-resolvers>
</mvc:annotation-driven>

和创建注释为的currentUser

and created an annotation for CurrentUser

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {

}

当我启动应用程序了类的构造,因为我可以看到日志消息准备就绪,但是当我注释一个控制器方法本身(在有注解@Controller的类)解析器不执行

When I start the application up the class is constructed as I can see the log message "Ready" but the resolver does not execute when I annotate a controller method as such (in a class that has @Controller annotation)

@RequestMapping(method = RequestMethod.POST, value = "/update")
public ModelAndView update(@RequestParam MultipartFile background, @CurrentUser Principal principal) {
 ...
}

如果我把断点在这两种方法中的CurrentUserArgumentResolver类,既没有工作。
所以不知道我缺少的是什么?

If I put breakpoints on either method in the CurrentUserArgumentResolver class, neither work.So not sure what I am missing?

推荐答案

OK我曾指出,春天已经解决Principal对象在我上面的例子,所以我的说法解析器没有踢。我已经懒并添加@CurrentUser注释现有的参数。

OK I worked out that Spring was already resolving the Principal object in my above example and so my argument resolver was not kicking in. I had been lazy and added the @CurrentUser annotation to an existing parameter.

所以我改变了我的例子

@RequestMapping(method = RequestMethod.POST, value = "/update")
public ModelAndView update(@RequestParam MultipartFile background, @CurrentUser Principal principal) {
  ...
}

使用我的用户模型类

to use my User model class

@RequestMapping(method = RequestMethod.POST, value = "/update")
public ModelAndView update(@RequestParam MultipartFile background, @CurrentUser User user) {
  ...
}

和现在的作品!

这篇关于春天HandlerMethodArgumentResolver不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 00:42