Practical 22: Write a Servlet program to send username and password using HTML forms and authenticate the user


MySrv.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySrv extends HttpServlet {


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

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  out.println("<HTML>");
  out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println("  <BODY>");


//Getting HTML parameters from Servlet

String username=request.getParameter("uname");
String password=request.getParameter("pwd");

if((username.equals("atharva")) && (password.equals("agrawal")))
  {
out.println("  <h1> Welcome to "+username);
        }
else
  {
out.println("  <h1>  Login fails ");
out.println("  <a href='./Registration.html'> Click for Home page </a>");
         }
  out.println("  </BODY>");
  out.println("</HTML>");
  out.close();
 }

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

}



Registration.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>

<BODY bgcolor='#e600e6'>
<form action='./MySrv' method="post">
<center> <h1> <u> Login Page </u></h1>

<h2>  Username : <input type="text"   name="uname"/><br>
           Password : <input type="password"   name="pwd"/><br>
         <input type="submit"   value="click me"/>   
</center>
</form>
</body>
</HTML>



Web.xml:
<web-app>
  <servlet>
    <servlet-name>MySrv</servlet-name>
    <servlet-class>MySrv</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MySrv</servlet-name>
    <url-pattern>/MySrv</url-pattern>
  </servlet-mapping>
  

<welcome-file-list>
    <welcome-file>Registration.html</welcome-file>
  </welcome-file-list>
</web-app>

Previous
Next Post »