Create the HTTP response

After the servlet request code, add the response code (in black text below):

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletSample extends HttpServlet
{

   public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
   {

      Enumeration keys;
      String key;
      String myName = "";
      keys = request.getParameterNames();
      while (keys.hasMoreElements())
      {
         key = (String) keys.nextElement();
         if (key.equalsIgnoreCase("myName")) myName = request.getParameter(key);
      }
      System.out.println("Name = ");
      if (myName == "") myName = "Hello";

      response.setContentType("text/html"); 
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");
	  
      PrintWriter out = response.getWriter(); 
      out.println("<html>"); 	
      out.println("<head><title>Just a basic servlet</title></head>");
      out.println("<body>");
      out.println("<h1>Just a basic servlet</h1>");
      out.println ("<p>" + myName +  ", this is a very basic servlet.");
      out.println("</body></html>");    
      out.flush();

   }
}

The HttpServletResponse object generates a response to return to the requesting client. Its methods allow you to set the response header and the response body.

The first line of the Response header (response.setContentType("text/html");) identifies the MIME type of the response. The following three lines are often placed in servlet code to prevent Web browsers and proxy servers from caching dynamically-generated Web pages. If you want your dynamic Web page to be cached, remove these three lines of code.

The response object also has the getWriter() method to return a PrintWriter object. The print() and println() methods of the PrintWriter object write the servlet response back to the client.