JavaRocks

 

We will write a example which will show how to access form fields from servlet.

 

To do so we need to create an html form and a servlet which reads all the parameters of html form.

The servlet will then show all the values it read form the form.

 

Following files will be required:

1. Deployment descriptor – (web.xml)2. html form (myform.html)3. servlet class (Class that extends HttpServlet)4. web server (Tomcat)
 

We will start with creating and html form.

 

Form.html


<html>
            <body>
                        <form action="MyServlet" method="post">
                                    Name: <input type="text" name="name">
                                    Company: <input type="text" name="company">
                                    <input type="submit">
                        </form>
            </body>
</html>
 

This form containsonly two fields name and company. This two fields will be accessed form servlet class and the values will be printed on the webpage.

 

MyServlet.class

 

package test;

 

import javax.servlet.http.HttpServlet;

import java.io.PrintWriter;

 

public class MyServlet extends HttpServlet {

    public void doGet(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws javax.servlet.ServletException, java.io.IOException{

        String name=httpServletRequest.getParameter("name");

        String company=httpServletRequest.getParameter("company");

        PrintWriter out=httpServletResponse.getWriter();

        out.print("User Info");

        out.print("<br>Name:"+name);

        out.print("<br>Company:"+company);

    }

}

 

web.xml

 

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
 <servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>test.MyServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>MyServlet</servlet-name>
 <url-pattern>/MyServlet</url-pattern>
 </servlet-mapping>
</web-app>


 

Run the web server and open the html form

Fill the form and click submit button.

 

http://localhost:8080/urAppName/form.html

 

The output should display the name and company you entered in html form.

Remember to open the html form using web server and not directly.(i.e not to open the html file directly by double clicking it)

 

    Sourabh Gandhi

    A Java Lover

    Archives

    April 2008

    Categories

    All

    RSS Feed