JSON Req/Res
Creating REST APIs in Java using servlets is a common approach for building web services. I'll provide you with an example of creating a simple REST API using a Java servlet that accepts JSON input and returns a JSON response. In this example, we will use the org.json
library for handling JSON.
First, ensure you have the
org.json
library in your classpath, as mentioned in a previous response.Create a Java servlet that handles JSON input and produces a JSON response. Here's a basic example:
In this example, we have created a servlet that listens to the POST
requests at the URL /api/example
. It reads the JSON input from the request and processes it using the org.json
library. Then, it constructs a JSON response and sends it back to the client.
Deploy your servlet in a servlet container like Apache Tomcat.
To test the REST API, you can use tools like
curl
, Postman, or a web application that can make HTTP POST requests with a JSON payload. Here's an example usingcurl
:
This curl
command sends a POST request with a JSON payload to your servlet, and you should receive a JSON response in return.
Please make sure to adapt the code and URL paths to your specific project and deployment setup. This example is for demonstration purposes, and in a production application, you may want to include error handling and additional validation.
Last updated