Servlets - Form Data & Basics of Web

Basics of Web-
There are some key points that must be known by the servlet programmer. Let's first briefly discuss these points before starting the servlet. These are:
  • HTTP
  • HTTP Request Types
  • Difference between Get and Post method
  • Container
  • Server
  • Difference between web server and application server
  • Content Type
  • Introduction of XML
  • Deployment
HTTP (Hyper Text Transfer Protocol)

Http is the protocol that allows web servers and browsers to exchange data over the web.It is a request response protocol.
Http Request Methods
Every request has a header that tells the status of the client. There are many request methods. Get and Post requests are mostly used. The http request methods are:
  • GET
  • POST
  • HEAD
  • PUT
  • DELETE
  • OPTIONS
  • TRACE
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.It is a HTTP header that provides the description about what are you sending to the browser.There are many content types:
  • text/html
  • text/plain
  • application/msword
  • application/vnd.ms-excel
  • application/jar
  • application/pdf
  • application/octet-stream
  • application/x-zip
  • images/jpeg
  • vedio/quicktime etc.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows:
http://www.dineshonjava.com/login?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limtation: only 1024 characters can be in a request string.

Anatomy of Get Request
As we know that data is sent in request header in case of get request. It is the default request type. Let's see what information are sent to the server.



This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method.
GET Method Example Using URL:
Here is a simple URL which will pass two values to HelloForm program using GET method.
http://localhost:8080/HelloServlet?user_name=Dinesh&password=Sweety
Below is HelloServlet.java servlet program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloServlet extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
   String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>User Name</b>: "
                + request.getParameter("user_name") + "\n" +
                "  <li><b>Password</b>: "
                + request.getParameter("password") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
}
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in D:\Servlet (Windows) or /usr/Servlet (Unix) then you would need to add these directories as well in CLASSPATH.\

Assuming your environment is setup properly, go in Servlet directory and compile HelloServlet.java as follows:
If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program.

If everything goes fine, above compilation would produce HelloServlet.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.

Servlet Deployment:
By default, a servlet application is located at the path C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\ and the class file would reside in C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\WEB-INF\classes.
For now, let us copy HelloServlet.class into /webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\/webapps/ROOT/WEB-INF/
<servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>



POST method:
A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method.

Anatomy of Post Request
As we know, in case of post request original data is sent in message body. Let's see how informations are passed to the server in case of post request. 


Reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the situation:
  • getParameter(): You call request.getParameter() method to get the value of a form parameter.
  • getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
  • getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloServlet extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
   String title = "Using POST Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>User Name</b>: "
                + request.getParameter("user_name") + "\n" +
                "  <li><b>Password</b>: "
                + request.getParameter("password") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
// Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}



<<Previous <<   || Index ||   >>Next >>








No comments:

Post a Comment