您可以仅从配置中获取此信息,无需编写任何特殊程序。操作方法如下:首先正确设置配置,我使用 Jackson + JAXB,两者都设置在 ContentNegotiatingViewResolver bean 下:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<oxm:jaxb2-marshaller id="marshaller">
<oxm:class-to-be-bound name="com.shay.dashboard.data.structure.page.PageObject" />
<oxm:class-to-be-bound name="com.shay.dashboard.data.structure.tab.TabObject" />
<oxm:class-to-be-bound name="com.shay.dashboard.data.structure.section.SectionObject" />
<oxm:class-to-be-bound name="com.shay.dashboard.data.structure.element.nonembedded.ElementObject"/>
<oxm:class-to-be-bound name="com.shay.dashboard.data.structure.element.embedded.EmbeddedElementObject"/>
<oxm:class-to-be-bound name="com.shay.dashboard.data.structure.chart.common.ChartManager"/>
</oxm:jaxb2-marshaller>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</list>
</property>
</bean>
请注意,在编组器下,我设置了 oxm:class-to-be-bound - 这些是 JAXB 绑定的类。
现在对于模块,我使用了非编组器特定的普通注释包(javax.xml.bind.annotation)。Jackson Json 和 JAXB 都知道如何阅读它。
例如:
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="page")
public class PageObject implements ComponentTypeObject{
@XmlAttribute(name="name")
private String name;
@XmlAttribute(name="id",required=true)
private String id;
@XmlElements({@XmlElement(name="tab", type=TabXmlAdapter.class)})
private List<TabXmlAdapter> tabRef;
最后,你的 MVC 控制器需要返回一个模型和视图:
@RequestMapping(value="/get_page", method = RequestMethod.GET)
public ModelAndView initPage()
{
ModelAndView mav = null;
try
{
PageObject myPage = (PageObject) Utilities.getUtilities().loadObjectFromFile(XmlComponentType.page);
mav = new ModelAndView("page","page",myPage);
}
catch (Exception e)
{
e.getMessage();
}
return mav;
}
现在,在调用以 .json 结尾的 URL 时,您将获得 JSON 表示,以及 .xml - 和 XML。两者都由查看器翻译,前提是您在注释模块时提供了正确的映射。