Servlets – Form Data

Servlets – Form Data ”; Previous Next You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your backend program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method. 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 ? (question mark) symbol as follows − http://www.test.com/hello?key1 = value1&key2 = value2 The GET method is the default 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 limitation: only 1024 characters can be used in a request string. 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. 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 method, but instead of sending it as a text string after a ? (question mark) 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. 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. GET Method Example using URL Here is a simple URL which will pass two values to HelloForm program using GET method. http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI Given below is the HelloForm.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 HelloForm 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>First Name</b>: ” + request.getParameter(“first_name”) + “n” + ” <li><b>Last Name</b>: ” + request.getParameter(“last_name”) + “n” + “</ul>n” + “</body>” + “</html>” ); } } Assuming your environment is set up properly, compile HelloForm.java as follows − $ javac HelloForm.java If everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/ <servlet> <servlet-name>HelloForm</servlet-name> <servlet-class>HelloForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloForm</servlet-name> <url-pattern>/HelloForm</url-pattern> </servlet-mapping> Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser”s Location:box and make sure you already started tomcat server, before firing above command in the browser. This would generate following result − Using GET Method to Read Form Data First Name: ZARA Last Name: ALI GET Method Example Using Form Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same Servlet HelloForm to handle this input. <html> <body> <form action = “HelloForm” method = “GET”> First Name: <input type = “text” name = “first_name”> <br /> Last Name: <input type = “text” name = “last_name” /> <input type = “submit” value = “Submit” /> </form> </body> </html> Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form. First Name: Last Name: Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example. POST Method Example Using Form Let us do little modification in the above servlet, so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { // Method to handle GET method request. 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>First Name</b>: ” + request.getParameter(“first_name”) + “n” + ” <li><b>Last Name</b>: ” + request.getParameter(“last_name”) + “n” + “</ul>n” + “</body>” “</html>” ); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as follows − <html> <body> <form action = “HelloForm” method = “POST”> First Name: <input type = “text” name = “first_name”> <br /> Last Name: <input type = “text” name = “last_name” /> <input type = “submit” value = “Submit” /> </form> </body> </html> Here is the actual output of the above

Servlets – Environment Setup

Servlets – Environment Setup ”; Previous Next A development environment is where you would develop your Servlet, test them and finally run them. Like any other Java program, you need to compile a servlet by using the Java compiler javac and after compilation the servlet application, it would be deployed in a configured environment to test and run.. This development environment setup involves the following steps − Setting up Java Development Kit This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately. You can download SDK from Oracle”s Java site − Java SE Downloads. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:jdk1.8.0_65, you would put the following line in your C:autoexec.bat file. set PATH = C:jdk1.8.0_65bin;%PATH% set JAVA_HOME = C:jdk1.8.0_65 Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8.0_65 and you use the C shell, you would put the following into your .cshrc file. setenv PATH /usr/local/jdk1.8.0_65/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.8.0_65 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Setting up Web Server − Tomcat A number of Web Servers that support servlets are available in the market. Some web servers are freely downloadable and Tomcat is one of them. Apache Tomcat is an open source software implementation of the Java Servlet and Java Server Pages technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine − Download latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:apache-tomcat-8.0.28 on windows, or /usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on windows machine − %CATALINA_HOME%binstartup.bat or C:apache-tomcat-8.0.28binstartup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-8.0.28/bin/startup.sh After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org Tomcat can be stopped by executing the following commands on windows machine − C:apache-tomcat-8.0.28binshutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − /usr/local/apache-tomcat-8.0.28/bin/shutdown.sh Setting Up the CLASSPATH Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler. If you are running Windows, you need to put the following lines in your C:autoexec.bat file. set CATALINA = C:apache-tomcat-8.0.28 set CLASSPATH = %CATALINA%commonlibservlet-api.jar;%CLASSPATH% Alternatively, on Windows NT/2000/XP, you could go to My Computer −> Properties −> Advanced −> Environment Variables. Then, you would update the CLASSPATH value and press the OK button. On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file. setenv CATALINA = /usr/local/apache-tomcat-8.0.28 setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH NOTE − Assuming that your development directory is C:ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH in similar way as you have added above. Print Page Previous Next Advertisements ”;

Servlets Tutorial

Servlets Tutorial PDF Version Quick Guide Resources Job Search Discussion Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. Why to Learn Servlet? Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI. Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. Applications of Servlet Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Audience This tutorial is designed for Java programmers with a need to understand the Java Servlets framework and its APIs. After completing this tutorial you will find yourself at a moderate level of expertise in using Java Servlets from where you can take yourself to next levels. Prerequisites We assume you have good understanding of the Java programming language. It will be great if you have a basic understanding of web application and how internet works. Print Page Previous Next Advertisements ”;