简体   繁体   English

从REST资源中的数据库结果集中返回XML

[英]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. 我正在尝试从REST资源(Jersey 2.x)以XML形式返回DB结果集为XML,但是我一直得到一个空结果。 No Error in the log files. 日志文件中没有错误。

Postman returns also: 200 Ok. 邮递员还返回:200 OK。 No errors. 没有错误。 The Request to the server passes one parameter which is userId: localhost:8080/messenger/webapi/v1/messages/userProfile?u=21 发送到服务器的请求传递一个参数,该参数是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. 泽西开箱即用地支持XML (通过JAXB ),因此无需手动将对象转换为xml表示形式。 The process is rather simple and involves 这个过程很简单,涉及

  • creating a POJO 创建一个POJO
  • populating and returning this POJO from your web service 从您的Web服务填充并返回此POJO

Your POJO 您的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. 请注意,您的WS方法将返回MyPOJO的实例,而不是String。 Sure, the framework will convert it to an XML representation. 当然,该框架会将其转换为XML表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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