Spring MVC ModelAttribute作为接口 [英] Spring MVC ModelAttribute as Interface

查看:63
本文介绍了Spring MVC ModelAttribute作为接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring MVC @Controller,如何让@RequestMapping终结点声明为接口的@ModelAttribute?

Using a Spring MVC @Controller, how do I have a @RequestMapping endpoint have a @ModelAttribute declared as an interface?

我希望将三种不同的形式发布到映射中,这些基础类都是接口类型.

I want to have three different forms being posted to the mapping that the underlying classes are all of an interface type.

例如,我可以拥有三个不同的表单对象,并具有以下作用:

So for example, I can have three different form objects with the action to the following:

@RequestMapping(path="/doSomething", method=RequestMethod.POST)
public String doSomething(ObjectInterface formInfo) {
   ...
}

(其中ObjectInterface是接口,而不是具体的类.)

(Where ObjectInterface is an interface, not a concrete class.)

推荐答案

弄清楚了.它是编写和注册一个自定义HandlerMethodArgumentResolver的方法.以下是核心代码.您只需要确定将哪个具体的bean类传递到webDataBinderFactory中即可.然后可以编写您的控制器以接受接口,并且将在接口后面为您提供具体的实现Bean.

Figured it out. It is to write and register a custom HandlerMethodArgumentResolver. Below is the core code. You just need to figure out which concrete bean class to pass into the webDataBinderFactory. Your controller can then be written to accept an interface and you will be provided the concrete implementing bean behind the interface.

public class MessageResolverTest implements HandlerMethodArgumentResolver {

    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(<Interface>.class);
    }

    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        String name = ModelFactory.getNameForParameter(methodParameter);
        WebDataBinder webDataBinder = webDataBinderFactory.createBinder(nativeWebRequest, new <ConcreteBean>(), name);
        MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(nativeWebRequest.getParameterMap());
        webDataBinder.bind(mutablePropertyValues);

        return webDataBinder.getBindingResult().getTarget();
    }
}

这篇关于Spring MVC ModelAttribute作为接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆