arsenal
arsenal

Reputation: 24144

Servlet that receives a XML based request and then make a new XML file to send back as the response

I am trying to create a Servlet that receives a XML based request and sends a XML in the response. I am new to Servlet first of all.

I have created the below Servlet in which I thought I am creating a Servlet that receives a XML based request in the doGet method and then in the doPost method, I can parse that XML file and then make a new XML file to send back the response. But I believe my understanding is wrong.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    response.setContentType("application/xml");
    PrintWriter writer = response.getWriter();
    writer.println("<?xml version=\"1.0\"?>");
    writer.println("<request uuid = \"hello\">");
    writer.println("<app hash = \"abc\"/>");
    writer.println("<app hash = \"def\"/>");
    writer.println("</request>");
    writer.flush();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    System.out.println(request);
       //parse the xml file if my understanding is right?
}

Can anyone provide me a simple example of this? I am just trying to create a Servlet that receives a XML based request (I am not sure of this, how can I make a servlet that can receive a XML based request), xml should be like above in my example.

And then parse the above XML file and use some content from that XML file to make a new sample XML file which I will be sending back as the response from that same Servlet.

Any help will be appreciated on this as I am slightly new to Servlet. This is the first time I am working with Servlet.

Update:-

I haven't got a proper answer on this yet. Any simple example will make me understand better. Thanks

Upvotes: 2

Views: 5395

Answers (1)

Keith
Keith

Reputation: 4184

You probably want to do everything in the doPost() method. Just one of doGet or doPost will be called, for a given HTTP request, depending on if the caller specified GET or POST in their request.

Your creation of the XML response looks basically ok. That is the general approach anyway, write the result XML to the response writer. If this is for production code, and not just a learning exercise, then you should use a library to create the XML, not just manually build it from strings. See "HOWTO Avoid Being Called a Bozo When Producing XML" http://hsivonen.iki.fi/producing-xml/

As far as parsing the incoming request:

BufferedReader reader = request.getReader()

Use that to read the characters of the incoming XML, and pass them to your XML parser.

Upvotes: 1

Related Questions