简体   繁体   中英

Returning XML from DB Result-Set in REST Resource

I'm trying to return DB Result-Set as XML from a REST Resource (Jersey 2.x), but I keep getting an empty result. No Error in the log files.

Postman returns also: 200 Ok. No errors. The Request to the server passes one parameter which is userId: localhost:8080/messenger/webapi/v1/messages/userProfile?u=21

ResultSet myRs;
StringWriter sw;

@Path("/userProfile")
@GET
@Produces(MediaType.APPLICATION_XML)
public String returnUserProfile(@QueryParam("u") int u) throws Exception {

    DocumentBuilderFactory theFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = theFactory.newDocumentBuilder();
    Document document = builder.newDocument();
    Element results = document.createElement("Results");

    try {
        conn = DaoMessenger.PostGresCon().getConnection();
        query = conn.prepareStatement ("SELECT * FROM users WHERE id ='" + u + "'" );
        ResultSet profileResult = query.executeQuery();

        ResultSetMetaData rsmd = profileResult.getMetaData();
        int columns = rsmd.getColumnCount();

        while (profileResult.next()) {
            Element theRow = document.createElement("Row");
            System.out.println("ROW -----> " + theRow);

            results.appendChild(theRow);

            for(int i = 1; i <= columns; i++){
                String columnName = rsmd.getColumnName(i);
                Object value = profileResult.getObject(i);
                Element nd = document.createElement(columnName);
                nd.appendChild( document.createTextNode( value.toString() ) );
                theRow.appendChild(nd);
                System.out.println("NODE: " + nd);
            }

            System.out.println("RESULTS ----> " + results);
        }

        DOMSource domSource = new DOMSource(document);
        TransformerFactory tf = TransformerFactory.newInstance();
        javax.xml.transform.Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        transformer.transform(domSource, sr);

        System.out.println("sw.toString(): " + sw.toString());

        query.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) conn.close();
    }
    return sw.toString();   
}

Any Idea Please? Should I change the Method Type to: Response and change the returned type?

Jersey supports XML (via JAXB ) out of the box so there's no need to manually convert an object to an xml represantation. The process is rather simple and involves

  • creating a POJO
  • populating and returning this POJO from your web service

Your POJO

@XmlRootElement
class MyPOJO{

      //fields and getters/setters
}

Your web service method

@Path("/userProfile")
@GET
@Produces(MediaType.APPLICATION_XML)
public MyPOJO returnUserProfile(@QueryParam("u") int u){

MyPOJO myPojo = new MyPOJO();
//populate myPojo's fields
//you will access your DB to populate the fields

return myPojo;

}
}

Note that your WS method will return an instance of MyPOJO, not a String. Sure, the framework will convert it to an XML representation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM