Java Servlet Request and Response are the objects use to communicate with clients. The HttpServletRequest interface provides methods for retrieving information about the request, while the HttpServletResponse interface provides methods for sending back a response to the client. Understanding how to use these objects is important for any Servlet programmer.
Table of Contents
Request and Response Examples
Using Request Object
Example of using the Request object to retrieve form data
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
// Do something with name and email
}
Response object to write HTML
Example of using the Response object to write HTML
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>My Page</title></head><body>");
out.println("<h1>Welcome to my page</h1>");
out.println("<p>This is some sample text</p>");
out.println("</body></html>");
}
Using Request and Response objects to perform a redirect
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("https://www.example.com");
}
Conclusion
HttpServletRequest and HttpServletResponse interfaces are essential for Java Servlet programming. The former handles incoming client requests while the latter manages the outgoing response.