一、SpringMvc提供了对excel,pdf,json,xml等多种视图支持 。本处就以xml格式来作为示例,其他的需要导入不同的jar包
XML视图需要导入的jar包:spring-oxm-4.1.2.RELEASE.jar
二、application.xml配置 (在上一篇 springmvc 全注解开发中的application.xml中配置即可)
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<!-- 配置支持媒体类型 -->
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"></entry>
<entry key="xml" value="application/xml"></entry>
<entry key="pdf" value="application/pdf"></entry>
</map>
</property>
</bean>
</property>
<!-- 指定默认视图 -->
<property name="defaultViews">
<!-- 支持多个视图 -->
<list>
<!-- 对josn格式视图支持 -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
<!-- xml格式视图支持 -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.shenzhenair.pojo.User</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
三、实体类加注解@XmlRootElement
package com.shenzhenair.pojo;
import lombok.Data;
import javax.xml.bind.annotation.XmlRootElement;
@Data
@XmlRootElement
public class User {
private String name;
private Integer age;
private boolean isMarry;
private double income;
private String[] interests;
}
四、代码示例
@Controller
@RequestMapping("/hello")
public class ParamController {
// 多视图支持
@RequestMapping(value = "/test17")
public User testMultiView(){
User user = new User();
user.setName("tom");
user.setMarry(true);
user.setIncome(22.0);
user.setAge(18);
return user;
}
}
五、访问路径及其结果
- json视图:
- XML视图: