February 26, 2011

Servlets - Handling a GET request

Write a servlet to handle a GET request. This request should send a response that is an HTML form for logging in.

package info.icontraining.servlets;

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

public class GetServlet extends HttpServlet {

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

      PrintWriter out = response.getWriter();
      out.println("<html>");
      out.println("<body>");
      out.println("<h2>Get Servlet Example</h2>");
      out.println("<form action=\"formurl\" method=\"post\">");
      out.println("Login<br/> ");
      out.println("<input type=\"text\" name=\"user\" /><br/>");
      out.println("Password<br/> ");
      out.println("<input type=\"password\" name=\"pass\" /><br/>");
      out.println("<input type=\"submit\" value=\"Login\" />");
      out.println("</form>");
      out.println("</body></html>");
      out.close();
  }
}


Add the following configuration in the web.xml,

<servlet>
   <servlet-name>getServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>getServlet</servlet-name>
   <url-pattern>/login</url-pattern>
</servlet-mapping>


Access the servlet by typing the following URL in the browser,

http://localhost:8080/WebAppName/login

2 comments:

  1. Syntax error in line 2 import java.io.* - no semicolon in the end. Not a big deal but just wanted to let you know.

    ReplyDelete