To get the response body from HttpServletResponse in Java, you can follow these steps:
- Get the PrintWriter object of the HttpServletResponse.
- Use the PrintWriter object to write the response content.
- Close the PrintWriter to commit the response and send it back to the client.
// Get the PrintWriter object from HttpServletResponse
PrintWriter writer = response.getWriter();
// Write response content to the PrintWriter
writer.println("This is the response body");
// Close the PrintWriter
writer.close();
Here’s a complete example:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the content type of the response
response.setContentType("text/html");
// Get the PrintWriter object from HttpServletResponse
PrintWriter writer = response.getWriter();
// Write response content to the PrintWriter
writer.println("This is the response body");
// Close the PrintWriter
writer.close();
}
}
In this example, we’re extending the HttpServlet class and overriding the doGet() method to handle GET requests. The response content type is set to “text/html”. We obtain the PrintWriter object from the HttpServletResponse and use it to write “This is the response body” to the response.
Once the PrintWriter is closed, the response is committed and sent back to the client.
- How do i fix runtime error 76 path not found in excel
- How to get repository id in azure devops
- How to generate xml file from excel using macro
- How to filter nested json data in python
- How to display console output in tkinter
- How to change json property name dynamically in c#
- How to display different navbar component for different reactjs pages
- How to get repository id in azure devops