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("<head><title>Post Servlet Example</title></head>"); 
      if (username.equals("dinesh") && passwd.equals("dinesh")) {
         out.println("Welcome " + username);
      } else {
         out.println("Incorrect username/password.");

Add the following configuration to the web.xml,


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

No comments:

Post a Comment