简体   繁体   English

Spring 3.1.0 MVC绑定模型属性与requestbody

[英]Spring 3.1.0 mvc binding modelattribute along with requestbody

I am new to Spring 3.1.0, and am trying to create an application, which can be exposed as a web application as well as web services. 我是Spring 3.1.0的新手,正在尝试创建一个可以作为Web应用程序和Web服务公开的应用程序。 For a POST where i am submitting a form object using the @ModelAttribute . 对于我使用@ModelAttribute提交表单对象的POST。 I also want to expose this method which can consume the same object as XML, through any poster. 我还想通过任何张贴者公开此方法,该方法可以使用与XML相同的对象。

Shall i use both @ModelAttribute & @RequestBody together. 我可以同时@ModelAttribute@RequestBody I have already added the consumes property in the @RequestMapping annotation. 我已经在@RequestMapping批注中添加了消耗属性。

When you submit form, data comes in form-encoded manner, and when you use XML/JSON it comes as a string in body. 提交表单时,数据以表单编码的方式出现,而当您使用XML / JSON时,数据作为正文中的字符串出现。 You'd better place all your common logic to intermediate service layer and call it in your controllers. 您最好将所有通用逻辑放入中间服务层,并在控制器中调用它。 As a result it allows you to simply build REST services on top of existing HTML pages with forms: 结果,它使您可以简单地在现有的HTML页面上使用表单构建REST服务:

public class Service {
    public void registerUser(User user){
    }
}

@RequestMapping("users")
public class FormController{
    @Autowired private Service service;

    @RequestMapping("register")
    public ModelAndView registerUser(@ModelAttribute User user){
        service.registerUser(user);
    }
}

@RequestMapping("service/v1")
public class RESTController{
    @Autowired private Service service;

    @RequestMapping("users/register")
    public ModelAndView registerUser(@RequestBody User user){
        service.registerUser(user);
    }
}

Actually, you can even put this in one controller. 实际上,您甚至可以将其放在一个控制器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM