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

public class MyFirstServlet extends HttpServlet {

    /*
     *The doGet() method gets called when you first request the page
     */
    public void doGet(HttpServletRequest p_request, HttpServletResponse p_response) throws IOException, ServletException {

	/*
	 * The HttpServletResponse object is what gets sent back to the client.
	 * Any html written to the PrintWriter will be displayed in the browser
	 */
        p_response.setContentType("text/html");
        PrintWriter x_out = p_response.getWriter();


	/* A helper function to write out the top html */
	writeHeader( x_out , "A Simple Form" );

        x_out.println("<h1>" + "A Simple Form" + "</h1>");


	/* html to specify the form, not the escaped quotes in the string */ 
	x_out.println("<form name=\"simple\" action=\"MyFirstServlet\" method=\"POST\" >");

	x_out.println("Please enter your name : ");
	x_out.println("<input type=\"text\" name=\"username\" />");
	x_out.println("<input type=\"submit\" name=\"submit\" value=\"submit\" />");
	x_out.println("</form>");


	/* close off the html */
	writeFooter( x_out );
    }

    /* 
     * the doPost() method gets called when data is submitted to the page, say
     * by clicking on the "submit" button in a form.
     */
    public void doPost( HttpServletRequest p_request, HttpServletResponse p_response ) throws ServletException, IOException {

	p_response.setContentType("text/html");
        PrintWriter x_out = p_response.getWriter();
	
	writeHeader( x_out , "A Simple Response" );


	/*
	 * parameter values can be retrieved from the response object. Note
	 * that the parameter name must match the name given to the input
	 * filed in the form (in goGet() above).
	 */
        x_out.println("<h1>Hello " + p_request.getParameter("username") + "</h1>");

	writeFooter( x_out );
    }

    private void writeHeader( PrintWriter p_out , String p_title ) {

	p_out.println("<html>");
	p_out.println("<head>");
	p_out.println("<title>" + p_title + "</title>");
	p_out.println("</head>");
	p_out.println("<body bgcolor=\"white\">");
    }

    private void writeFooter( PrintWriter p_out ) {

	p_out.println("</body>");
	p_out.println("</html>");	
    }
}