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.
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