【问题标题】:issues with xml in spring mvc 3spring mvc 3中的xml问题
【发布时间】:2011-09-20 17:45:52
【问题描述】:

请看我下面的 4 个简单示例,其中 2 个适用于 xml,另外 2 个不适用。

//works for html, json, xml
     @RequestMapping(value = "/test", method = RequestMethod.GET)
            public ModelAndView testContentNegiotation(HttpServletRequest request, HttpServletResponse response) {

                ModelAndView mav = new ModelAndView();

                    TestTO test =  new TestTO("some msg", -888);
                    mav.addObject("test", test);

                    mav.setViewName("test"); //test is a jsp page

                return mav;
            }

//does not work for xml
     @RequestMapping(value = "/test", method = RequestMethod.GET)
            public ModelAndView testContentNegiotation(HttpServletRequest request, HttpServletResponse response) {

                ModelAndView mav = new ModelAndView();

                    ErrorTO error =  new ErrorTO("some error", -111);
                    mav.addObject("error",error );

                    TestTO test =  new TestTO("some msg", -888);
                    mav.addObject("test", test);

                    mav.setViewName("test");

                return mav;
            }

         //works for xml and json   
@RequestMapping(value = "/test3", method = RequestMethod.GET)
    public @ResponseBody ErrorTO test3(HttpServletRequest request, HttpServletResponse response) {

        ErrorTO error = new ErrorTO();
        error.setCode(-12345);
        error.setMessage("this is a test error.");
        return error;
    }

//does not work for xml
            @RequestMapping(value = "/testlist", method = RequestMethod.GET)
            public @ResponseBody List<ErrorTO> testList2(HttpServletRequest request, HttpServletResponse response) {

                    ErrorTO error =  new ErrorTO("an error", 1);
                    ErrorTO error2 =  new ErrorTO("another error", 2);
                    ArrayList<ErrorTO> list = new ArrayList<ErrorTO>();
                    list.add(error);
                    list.add(error2);
                    return list;

            }

在两个不能生成xml的例子中,是否可以通过配置spring来使其工作呢?

【问题讨论】:

    标签: xml json spring spring-mvc content-negotiation


    【解决方案1】:

    不生成 XML 的两个示例不起作用,因为您的模型中有多个顶级对象。 XML 无法表示 - 您需要一个可以转换为 XML 的模型对象。同样,Spring MVC 也无法将裸列表转换为 XML。

    在这两种情况下,您都需要将各种模型对象包装到单个根对象中,然后将其添加到模型中。

    另一方面,JSON 在单个文档中表示多个顶级对象没有问题。

    【讨论】:

    • 我也是这么想的。那么您对此有何建议?我想我必须创建新的 jaxb bean 来保存这些不同的模型对象,如果您考虑最终将创建多少个 bean,这会很痛苦。另外,您是否会建议使用同时生成 html 和 json 的方法来执行此操作,或者以单独的方法执行此操作?非常感谢!
    猜你喜欢
    • 2011-06-29
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2011-06-27
    相关资源
    最近更新 更多