2011-06-22 37 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