Thursday, April 12, 2012

Invoking Servlets from HTML form


INVOKING SERVLETS FROM HTML FORM

AIM:

To write a java program to invoke servlets from HTML form.

ALGORITHM:

client.html
(1)  Create a web page using HTML form that contains the fields such as text, password and one submit button.
(2)  Set the URL of the server as the value of form’s action attribute.
(3)  Run the HTML program.
(4)  Submit the form data to the server.
server.java
(1)  Define the class server that extends the property of the class GenericServlet.
(2)  Handle the request from the client by using the method service() of GenericServlet class.
(3)  Get the parameter names from the HTML form by using the method getParameterNames().
(4)  Get the parameter values from the HTML forms by using the method getParameter().
(5)  Send the response to the client by using the method of PrintWriter class.

server.java:

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class server extends GenericServlet
{
 public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
 {
  PrintWriter pw=res.getWriter();
  pw.print("<h3>Registration Successful...</h3>");
  Enumeration e=req.getParameterNames();
  while(e.hasMoreElements())
  {
   String str1=(String)e.nextElement();
   String str2=req.getParameter(str1);
   pw.print(str1+"="+str2+"<br/>");
  }
  pw.close();
 }
}

web.xml:
<web-app>
 <servlet>
        <servlet-name>Register</servlet-name>
        <servlet-class>server</servlet-class>
    </servlet>

<servlet-mapping>
        <servlet-name>Register</servlet-name>
        <url-pattern>/server</url-pattern>
    </servlet-mapping>
</web-app>

Client.HTML:

<html>
<head>
<title>Invoking Servlet From HTML</title>
</head>
<body bgcolor="violet">
<form name="form1" method="post" action="http://localhost:8080/servlets1/server">
<fieldset>
<legend>Registration</legend>
Enter E-mail&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="LoginID" size="25"/><br/><br/>
Enter Password:
<input type="password" name="Password" size="25">
<input type="submit" Value="SUBMIT">
</fieldset>
</form>
</body>
</html>

8 comments: