I. GENERAL description
XML and JSON are the most commonly used data interchange formats. This example shows how to turn a Java object into an XML output.
Second, the process
1. In the example above, create a package "Com.waylau.rest.bean"
2. Create a Java class "User" under the package
[Java]View Plaincopyprint?
- Package Com.waylau.rest.bean;
- Import javax.xml.bind.annotation.XmlRootElement;
- /*
- * User Bean
- * @author waylau.com
- * 2014-3-17
- */
- @XmlRootElement
- Public class User {
- private String userId;
- private String UserName;
- private String age;
- Public User () {};
- Public User (string userId, String userName, String age) {
- This.userid = userId;
- this.username = userName;
- this.age = age;
- }
- Public String getUserId () {
- return userId;
- }
- public void Setuserid (String userId) {
- This.userid = userId;
- }
- Public String GetUserName () {
- return userName;
- }
- public void Setusername (String userName) {
- this.username = userName;
- }
- Public String Getage () {
- return age;
- }
- public void Setage (String age) {
- this.age = age;
- }
- }
Note: This class adds an annotation "@XmlRootElement" that is the root node of the XML when it is converted to XML.
3. In "Com.waylau.rest.resources", add the Resource "Userresource" with the following code:
[Java]View Plaincopyprint?
- Package com.waylau.rest.resources;
- Import java.util.ArrayList;
- Import Java.util.HashMap;
- Import java.util.List;
- Import Java.util.Map;
- Import Javax.ws.rs.Path;
- Import javax.ws.rs.Produces;
- Import Javax.ws.rs.PathParam;
- Import Javax.ws.rs.core.MediaType;
- Import Javax.ws.rs.DELETE;
- Import Javax.ws.rs.GET;
- Import Javax.ws.rs.POST;
- Import Javax.ws.rs.PUT;
- Import Com.waylau.rest.bean.User;
- @Path ("/users")
- Public class Userresource {
- private static map<string,user> UserMap = new hashmap<string,user> (); Store users
- /**
- * Check All
- * @return
- */
- @GET
- @Produces (mediatype.application_xml)
- Public list<user> getAllUsers () {
- list<user> users = new arraylist<user> ();
- User U1 = new User ("001","Waylau","26");
- User U2 = new User ("002","King","23");
- User U3 = new User ("003","Susan","21");
- Usermap.put (U1.getuserid (), U1);
- Usermap.put (U2.getuserid (), U2);
- Usermap.put (U3.getuserid (), U3);
- Users.addall (Usermap.values ());
- return users;
- }
- @GET
- @Path ("/getuserxml")
- @Produces (mediatype.application_xml)
- Public User Getuserxml () {
- User user = new user ();
- User.setage ("21");
- User.setuserid ("004");
- User.setusername ("Amand");
- return user;
- }
- }
Where Mediatype.application_xml shows that the output is in XML form
Output a single object in the browser input http://localhost:8089/RestDemo/rest/users/getUserXml
A collection of Http://localhost:8089/RestDemo/rest/users output objects in the browser input
This article transferred from: http://blog.csdn.net/kkkloveyou/article/details/21415735
Jersey building restful style of Webserivices (ii)