1、在springmvc.xml中加上
<!-- 多视图的支持 -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"/>
</property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.xiaostudy.domain.User</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
2、在支持多视图的类中加上注释@XmlRootElement
package com.xiaostudy.domain;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
private int id;
private String username;
private String password;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]";
}
}
3、使用
package com.xiaostudy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xiaostudy.domain.User;
@Controller//<bean class="com.xiaostudy.controller.MyController"/>
@RequestMapping(value="/myController")//访问该类的方法时,前面多这样一个路径
public class MyController {
@RequestMapping("multiView")
public User multiView() {
User user = new User();
user.setId(2018);
user.setUsername("xiaostudy");
user.setPassword("123456");
user.setAge(23);
return user;
}
}
4、访问