In this article I would like to describe how to get your RESTful webservice to output XML. RESTful doesnt output as much detail as the SOAP specification, but it gives you enough data to work with, assuming you know what the data types are.
Firstly, create a class that represents your output. Remember the import!
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class userData { public String firstname; public String lastname; public String idnumber; public String pin; public int status; } |
Then we can start coding the webservice. I’m not going to go into detail, but am just going to put in the specifics that are relevant for this article
import java.util.ArrayList; import java.util.List; @Path("airtime_functions") public class airtime { @GET @Path("get_users") @Produces("application/xml") public List<userData> get_users(@QueryParam("user_id") String user_id) { List<userData> retUser = new ArrayList<userData>(); try { errorMsg = ""; con = getJNDIConnection(); stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql = "SELECT * from users where user_id = ?"; PreparedStatement prest = con.prepareStatement(sql); prest.setString(1, user_id); prest.execute(); rs = prest.getResultSet(); while (rs.next()) { userData toReturn = new userData(); toReturn.firstname = rs.getString("firstname"); toReturn.idnumber = rs.getString("idnumber"); toReturn.lastname = rs.getString("surname"); toReturn.pin = rs.getString("pin"); toReturn.status = rs.getInt("status"); retUser.add(toReturn); } con.close(); return retUser; } catch (Exception e) { userData toReturn = new userData(); toReturn.firstname = "Error: " + e; toReturn.idnumber = ""; toReturn.lastname = ""; toReturn.pin = ""; toReturn.status = 0; retUser.add(toReturn); return retUser; } } |
To access this resource we do it something like this http://localhost:8080/this_ws_name/airtime_functions/get_users?user_id=1
That should send an XML packet containing the data back to your client. From there it is up to you what you want to do with it
I hope this helps make RESTful a little bit simpler

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 
New Blog Post -> Create XML output with RESTful webservices in JAVA – http://www.zayinkrige.com/create-xml-out…
[...] This post was mentioned on Twitter by Zayin Krige, Zayin Krige. Zayin Krige said: New Blog Post -> Create XML output with RESTful webservices in JAVA – http://toast.tw/100cd1 [...]