1. 程式人生 > >springMVC多視圖的支持

springMVC多視圖的支持

rri 支持 username fault entry control str code types

1、在springmvc.xml中加上

 1 <!-- 多視圖的支持 -->
 2         <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 3             <property name="contentNegotiationManager">
 4                 <bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"
/> 5 </property> 6 <property name="mediaTypes"> 7 <map> 8 <entry key="json" value="application/json"/> 9 <entry key="xml" value="application/xml"/> 10 </map> 11 </
property> 12 <property name="defaultViews"> 13 <list> 14 <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> 15 <bean class="org.springframework.web.servlet.view.xml.MarshallingView"
> 16 <constructor-arg> 17 <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> 18 <property name="classesToBeBound"> 19 <list> 20 <value>com.xiaostudy.domain.User</value> 21 </list> 22 </property> 23 </bean> 24 </constructor-arg> 25 </bean> 26 </list> 27 </property> 28 </bean>

2、在支持多視圖的類中加上註釋@XmlRootElement

 1 package com.xiaostudy.domain;
 2 
 3 import javax.xml.bind.annotation.XmlRootElement;
 4 
 5 @XmlRootElement
 6 public class User {
 7 
 8     private int id;
 9     private String username;
10     private String password;
11     private int age;
12 
13     public int getId() {
14         return id;
15     }
16 
17     public void setId(int id) {
18         this.id = id;
19     }
20 
21     public String getUsername() {
22         return username;
23     }
24 
25     public void setUsername(String username) {
26         this.username = username;
27     }
28 
29     public String getPassword() {
30         return password;
31     }
32 
33     public void setPassword(String password) {
34         this.password = password;
35     }
36 
37     public int getAge() {
38         return age;
39     }
40 
41     public void setAge(int age) {
42         this.age = age;
43     }
44 
45     @Override
46     public String toString() {
47         return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]";
48     }
49 
50 }

3、使用

 1 package com.xiaostudy.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 import com.xiaostudy.domain.User;
 7 
 8 @Controller//<bean class="com.xiaostudy.controller.MyController"/>
 9 @RequestMapping(value="/myController")//訪問該類的方法時,前面多這樣一個路徑
10 public class MyController {
11     
12     @RequestMapping("multiView")
13     public User multiView() {
14         User user = new User();
15         user.setId(2018);
16         user.setUsername("xiaostudy");
17         user.setPassword("123456");
18         user.setAge(23);
19         return user;
20     }
21 
22 }

4、訪問

技術分享圖片

技術分享圖片


springMVC多視圖的支持