Multi-view legend using content negotiation
Based on the introduction in the previous article, the example is provided here.
Configure XML
<Context: component-scan base-package ="Com. Controls"/>
<Context: annotation-config/>
<Bean class ="Org. springframework. Web. servlet. View. contentnegotiatingviewresolver">
<Property name ="Order"Value ="1"/>
<Property name ="Favorparameter"Value ="False"/>
<Property name ="Ignoreacceptheader"Value ="True"/>
<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>
<Bean class ="Org. springframework. Web. servlet. View. xml. marshallingview">
<Constructor-Arg>
<Bean class ="Org. springframework. oxm. jaxb. jaxb2marshaller">
<Property name ="Classestobebound">
<List>
<Value> com. model. User </value>
</List>
</Property>
</Bean>
</Constructor-Arg>
</Bean>
</List>
</Property>
</Bean>
<! -- This view parser will be used if none of the above matches -->
<Bean class ="Org. springframework. Web. servlet. View. internalresourceviewresolver">
<Property name ="Order"Value ="2"/>
<Property name ="Prefix"Value =/WEB-INF/views /"/>
<Property name ="Suffix"Value =". Jsp"/>
<Property name ="Viewclass"Value ="Org. springframework. Web. servlet. View. jstlview"/>
</Bean>
Model
@ Xmlrootelement
Public ClassUser {
Private LongUserid;
PrivateString username;
PrivateDate birth;
PublicString GetUserName (){
ReturnUsername;
}
Public VoidSetusername (string username ){
This. Username = username;
}
PublicDate getbirth (){
ReturnBirth;
}
Public VoidSetbirth (date Birth ){
This. Birth = birth;
}
Public LongGetuserid (){
ReturnUserid;
}
Public VoidSetuserid (LongUserid ){
This. Userid = userid;
}
}
Contoller
@ Requestmapping (value = "/user/{userid }")
PublicString queryuser (@ pathvariable ("userid ")LongUserid, modelmap Model)
{
User u =NewUser ();
U. setuserid (userid );
U. setusername ("Zhaoyang ");
Model. addattribute ("user", U );
Return"User ";
}
If text/html is returned, you also need to create a JSP file
<Body>
Username: $ {requestscope. User. userid} <br/>
Age: $ {requestscope. User. Username}
</Body>
Test Results
JSON
XML
JSP