Retrieving the XML payload in Java Servlet:
If the request content type is text/xml and the method is POST, we can use the below code to retrieve the xml payload in servlet.
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
BufferedReader br = request.getReader();
String line = null;
StringBuffer inputXML = new StringBuffer();
PrintWriter pout = response.getWriter();
while ((line = br.readLine()) != null) {
inputXML.append(line);
}
br.close();
System.out.println("Input "+inputXML);
java.io.InputStream sbis = new java.io.StringBufferInputStream(inputXML.toString());
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
b.setNamespaceAware(false);
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilder db = null;
try {
db = b.newDocumentBuilder();
doc = db.parse(sbis);
} catch (Exception e) {
e.printStackTrace();
}
org.w3c.dom.Element element = doc.getDocumentElement();
String empName=getPayloadValue(element, "EmpName");
String empNo=getPayloadValue(element, "EmpNo");
String output="<EmployeeCollection xmlns=\"http://xmlns.oracle.com/HttpAdapter/InvokeServlet/InvokeServlet\"><Employee><EmpName>"+empName+"</EmpName><EmpNo>"+empNo+"</EmpNo><EmpAge>27</EmpAge></Employee><Employee><EmpName>"+empName+"</EmpName><EmpNo>"+empNo+"</EmpNo><EmpAge>28</EmpAge></Employee></EmployeeCollection>";
out.write(output);
out.close();
}
public String getPayloadValue(Element taskPayloadElement, String nodeName){
String output= "";
NodeList nodeList = taskPayloadElement.getElementsByTagName(nodeName);
if(nodeList!=null && nodeList.getLength() > 0){
Element myElement = (Element)nodeList.item(0);
output= myElement.getFirstChild().getNodeValue();
}
return output;
}
public String getPayloadValue(Element taskPayloadElement, String nodeName){
String output= "";
NodeList nodeList = taskPayloadElement.getElementsByTagName(nodeName);
if(nodeList!=null && nodeList.getLength() > 0){
Element myElement = (Element)nodeList.item(0);
output= myElement.getFirstChild().getNodeValue();
}
return output;
}
No comments:
Post a Comment