【问题标题】:How to get json request in spring controller?如何在spring控制器中获取json请求?
【发布时间】:2013-05-06 09:50:29
【问题描述】:

这是我的控制器的代码。

@RequestMapping(value="/save", method=RequestMethod.POST )
public ModelAndView  saveArticle(@ModelAttribute Article article, BindingResult result) {
                     System.out.println("inside controller"+article.getArticleName()+"  "+article.getArticleDesc());
                     int a=articleService.addArticle(article);

                    if(a==1)
                    {
                        return new ModelAndView("success");
                    }
                    else
                    {
                        return new ModelAndView( "error");
                    }
                     /*else if(a==0){
                         return new ModelAndView("error");
                     }*/
                    //return new ModelAndView("redirect:/articles.html");
        }

如何获取json格式发送的articleName和desc,然后转换成java对象?

【问题讨论】:

    标签: json spring


    【解决方案1】:

    你可以使用@RequestBody注解。

    http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html

    您还可以包含jackson 来序列化/反序列化对象。

    @RequestMapping(value="/save", method=RequestMethod.POST )
    public ModelAndView  saveArticle(@RequestBody Article article, BindingResult result) {
        ...
    }
    

    【讨论】:

    • 如何在spring动态web项目中包含jackson?
    • 下载你需要的jar包,放到你的WEB-INF/lib目录下。找到罐子的一种简单方法是通过mvnrepository 网站。 mvnrepository.com/artifact/com.fasterxml.jackson.core
    • 我在使用@RequestBody 时得到http 状态415。我配置dispatcherservlet 如下。
    • 确保 XMLHttpRequest 设置了 Content-Type: application/json 标头。
    • 您能告诉我我需要在调度程序 Servlet 中更改哪些内容吗?
    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多