2011-06-22 36 views
1

请参阅我的以下4个简单示例,其中2个适用于xml,其他2个不适用。xml在spring mvc中的问题3

//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使它工作?

回答

4

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

在这两种情况下,都需要将各种模型对象封装到一个根对象中,然后将其添加到模型中。另一方面,JSON在单个文档中表示多个顶级对象时没有问题。

+0

这就是我的想法。那么你的建议是什么?我想我必须创建新的jaxb bean来容纳这些不同的模型对象,如果想想最终会创建多少个bean,这会很痛苦。你也可以推荐在产生html和json的方法中使用它,或者在sperate方法中使用它?非常感谢! – Bobo