JSON Response

A basic Java servlet program that handles both GET and POST requests and returns JSON responses. This example uses the javax.servlet and javax.servlet.http packages for handling HTTP requests and responses, and the org.json library for JSON processing. Make sure you have the org.json library in your classpath, which you can download from here: https://github.com/stleary/JSON-java.

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.json.JSONObject;

public class JsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Create a JSON object with some sample data
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "This is a GET request");
        jsonObject.put("method", "GET");

        // Set response content type to JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // Write the JSON object to the response
        response.getWriter().write(jsonObject.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Create a JSON object with some sample data
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "This is a POST request");
        jsonObject.put("method", "POST");

        // Set response content type to JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // Write the JSON object to the response
        response.getWriter().write(jsonObject.toString());
    }
}

In this servlet, we override both the doGet and doPost methods to handle GET and POST requests. Inside each method, we create a JSON object with some sample data and send it as the response. The content type of the response is set to "application/json," and the JSON object is written to the response's output stream.

Don't forget to configure your web.xml or use annotations to map the servlet to a URL pattern, depending on your web application setup.

Last updated