February 26, 2011

Servlets - Handling a POST request

Write a servlet to handle a POST request. This request should procure the form data on the server side and send an HTML response that prints "Welcome [username]" or "Incorrect username/password" based on whether login was successful or a failure.

package info.icontraining.servlets;

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

public class PostServlet extends HttpServlet {
 
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      String username = request.getParameter("user");
      String passwd = request.getParameter("pass");
      out.println("<html>");
      out.println("<head><title>Post Servlet Example</title></head>"); 
      out.println("<body><h1>");
       
      if (username.equals("dinesh") && passwd.equals("dinesh")) {
         out.println("Welcome " + username);
      } else {
         out.println("Incorrect username/password.");
      }
       
      out.println("</h1></body></html>");
      out.close();
   }
}

Add the following configuration to the web.xml,

<servlet>
   <servlet-name>postServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.PostServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>postServlet</servlet-name>
   <url-pattern>/formurl</url-pattern>
</servlet-mapping>


The servlet can be accessed through the GET Servlet at this URL

No comments:

Post a Comment