Alok
Alok

Reputation: 229

Sending and Receiving JSON data from a Servlet

How can I send JSON data to my Servlet's doPost() method and receive it back? I have a web service which produces and consumes JSON.

Upvotes: 1

Views: 6207

Answers (1)

Rocky
Rocky

Reputation: 951

Use the HttpServletRequest and HttpServletResponse arguments that are passed to your doPost method in a servlet

public class ExampServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
  {
    // to accept the json data

    String jsonData = request.getParameter("json");  

    // to send out the json data

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.println(jsonData) ; 
    out.close() /
   }

Upvotes: 3

Related Questions