XML 和 Json

XML

Spring MVC 还可以将模型中的数据以 XML 的形式输出,其对应的视图对象为 MarshallingView。下面在 smart-servlet.xml 中添加 MarshallingView 的配置,如下面代码所示。

<bean id="userListXml"
    class="org.springframework.web.servlet.view.xml.MarshallingView"
    p:modelKey="userList" p:marshaller-ref="xmlMarshaller"/>
<bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="streamDriver">
        <bean class="com.thoughtworks.xstream.io.xml.StaxDriver"/>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>com.smart.domain.User</value>
        </list>
    </property>
</bean>

MarshallingView 使用 Marshaller 将模型数据转换为 XML,通过 marshaller 属性注入一个 Marshaller 实例。在默认情况下,MarshallingView 会将模型中的所有属性都转换为 XML。由于模型属性包含很多隐式数据,直接将模型中的所有数据全部输出往往并不是我们所期望的。MarshallingView 允许通过 modelKey 指定模型中的哪个属性需要输出为 XML。

在 UseController 中添加一个处理方法,返回 userListXml 逻辑视图名。

@RequestMapping(value = "/showUserListByXml")
public String showUserListInXml(ModelMap mm) {
    Calendar calendar = new GregorianCalendar();
    List<User> userList = new ArrayList<User>();
    User user1 = new User();
    user1.setUserName("tom");
    user1.setRealName("汤姆");
    calendar.set(1980, 1, 1);
    user1.setBirthday(calendar.getTime());
    User user2 = new User();
    user2.setUserName("john");
    user2.setRealName("约翰");
    user2.setBirthday(calendar.getTime());
    userList.add(user1);
    userList.add(user2);
    mm.addAttribute("userList", userList);
    return "userListXml";
}

在浏览器地址栏中输入如下 URL 时,将返回 XML 内容的响应。

http://localhost:8080/chapter17/user/showUserListByXml.html

JSON

Spring 4.0 MVC 的 MappingJackson2JsonView 借助 Jackson 框架的 ObjectMapper 将模型数据转换为 JSON 格式输出。由于 MappingJackson2JsonView 也是一个Bean,可以通过 BeanNameViewResolver 进行解析,因此仅需在 smart-servlet.xml 中直接配置即可·

<bean id="userListJson"
  class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"
  p:modelKeys="userList"/>

在默认情况下,MappingJackson2JsonView 会将模型中的所有数据全部输出为 JSON,这显然是不适合的,可以通过 modelKeys 指定模型中的哪些属性需要输出。

在 UserController 中添加一个返回 userListJson 逻辑视图名的方法。

@RequestMapping(value = "/showUserListByJson")
public String showUserListInJson(ModelMap mm) {
    Calendar calendar = new GregorianCalendar();
    List<User> userList = new ArrayList<User>();
    User user1 = new User();
    user1.setUserName("tom");
    user1.setRealName("汤姆");
    calendar.set(1980, 1, 1);
    user1.setBirthday(calendar.getTime());
    User user2 = new User();
    user2.setUserName("john");
    user2.setRealName("约翰");
    user2.setBirthday(calendar.getTime());
    userList.add(user1);
    userList.add(user2);
    mm.addAttribute("userList", userList);
    return "userListJson";
}

在浏览器地址栏中输入以下地址将以 JSON 格式输出模型中名为 userList 的属性对象。

http://localhost:8080/chapter17/user/showUserListByJson.html
原文地址:https://www.cnblogs.com/jwen1994/p/11182411.html