JSON Response
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());
}
}Last updated