Servlets – Internationalization

Servlets – Internationalization ”; Previous Next Before we proceed, let me explain three important terms − Internationalization (i18n) − This means enabling a web site to provide different versions of content translated into the visitor”s language or nationality Localization (l10n) − This means adding resources to a web site to adapt to a particular geographical or cultural region. locale − This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which is separated by an underscore. For example “en_US” represents English locale for US. There are number of items which should be taken care while building up a global website. This tutorial would not give you complete detail on this but it would give you a good example on how you can offer your web page in different languages to internet community by differentiating their location i.e. locale. A servlet can pickup appropriate version of the site based on the requester”s locale and provide appropriate site version according to the local language, culture and requirements. Following is the method of request object which returns Locale object. java.util.Locale request.getLocale() Detecting Locale Following are the important locale methods which you can use to detect requester”s location, language and of course locale. All the below methods display country name and language name set in requester”s browser. Sr.No. Method & Description 1 String getCountry() This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format. 2 String getDisplayCountry() This method returns a name for the locale”s country that is appropriate for display to the user. 3 String getLanguage() This method returns the language code in lower case for this locale in ISO 639 format. 4 String getDisplayLanguage() This method returns a name for the locale”s language that is appropriate for display to the user. 5 String getISO3Country() This method returns a three-letter abbreviation for this locale”s country. 6 String getISO3Language() This method returns a three-letter abbreviation for this locale”s language. Example This example shows how you display a language and associated country for a request − import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; public class GetLocale extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the client”s Locale Locale locale = request.getLocale(); String language = locale.getLanguage(); String country = locale.getCountry(); // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); String title = “Detecting Locale”; 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”>” + language + “</h1>n” + “<h2 align = “center”>” + country + “</h2>n” + “</body> </html>” ); } } Languages Setting A servlet can output a page written in a Western European language such as English, Spanish, German, French, Italian, Dutch etc. Here it is important to set ContentLanguage header to display all the characters properly. Second point is to display all the special characters using HTML entities, For example, “&#241;” represents “ñ”, and “&#161;” represents “¡” as follows: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; public class DisplaySpanish extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); // Set spanish language code. response.setHeader(“Content-Language”, “es”); String title = “En Espa&ntilde;ol”; 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>” + “En Espa&ntilde;ol:” + “</h1>n” + “<h1>” + “&iexcl;Hola Mundo!” + “</h1>n” + “</body> </html>” ); } } Locale Specific Dates You can use the java.text.DateFormat class and its static getDateTimeInstance() method to format date and time specific to locale. Following is the example which shows how to format dates specific to a given locale − import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; import java.text.DateFormat; import java.util.Date; public class DateLocale extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); //Get the client”s Locale Locale locale = request.getLocale( ); String date = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT, locale).format(new Date( )); String title = “Locale Specific Dates”; 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”>” + date + “</h1>n” + “</body> </html>” ); } } Locale Specific Currency You can use the java.txt.NumberFormat class and its static getCurrencyInstance() method to format a number, such as a long or double type, in a locale specific currency. Following is the example which shows how to format currency specific to a given locale − import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; import java.text.NumberFormat; import java.util.Date; public class CurrencyLocale extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); //Get the client”s Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getCurrencyInstance(locale); String formattedCurr = nft.format(1000000); String title = “Locale Specific Currency”; 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”>” + formattedCurr + “</h1>n” + “</body> </html>” ); } } Locale Specific Percentage You can use the java.txt.NumberFormat class and its static getPercentInstance() method to get locale specific percentage. Following is the example which shows how to format percentage specific to a given locale − import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Locale; import java.text.NumberFormat; import java.util.Date; public class PercentageLocale extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); //Get the client”s Locale Locale locale = request.getLocale( ); NumberFormat nft = NumberFormat.getPercentInstance(locale); String formattedPerc = nft.format(0.51); String title = “Locale Specific Percentage”; String docType = “<!doctype html

Servlets – Cookies Handling

Servlets – Cookies Handling ”; Previous Next Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies. There are three steps involved in identifying returning users − Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. This chapter will teach you how to set or reset cookies, how to access them and how to delete them. The Anatomy of a Cookie Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser”s headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name = xyz A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects. Servlet Cookies Methods Following is the list of useful methods which you can use while manipulating cookies in servlet. Sr.No. Method & Description 1 public void setDomain(String pattern) This method sets the domain to which cookie applies, for example tutorialspoint.com. 2 public String getDomain() This method gets the domain to which cookie applies, for example tutorialspoint.com. 3 public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don”t set this, the cookie will last only for the current session. 4 public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. 5 public String getName() This method returns the name of the cookie. The name cannot be changed after creation. 6 public void setValue(String newValue) This method sets the value associated with the cookie 7 public String getValue() This method gets the value associated with the cookie. 8 public void setPath(String uri) This method sets the path to which this cookie applies. If you don”t specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. 9 public String getPath() This method gets the path to which this cookie applies. 10 public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections. 11 public void setComment(String purpose) This method specifies a comment that describes a cookie”s purpose. The comment is useful if the browser presents the cookie to the user. 12 public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment. Setting Cookies with Servlet Setting cookies with servlet involves three steps − (1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie(“key”,”value”); Keep in mind, neither the name nor the value should contain white space or any of the following characters − [ ] ( ) = , ” / ? @ : ; (2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours. cookie.setMaxAge(60 * 60 * 24); (3) Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header as follows − response.addCookie(cookie); Example Let us modify our Form Example to set the cookies for first and last name. // 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 { // Create cookies for first and last names. Cookie firstName = new Cookie(“first_name”, request.getParameter(“first_name”)); Cookie lastName = new Cookie(“last_name”, request.getParameter(“last_name”)); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); String title = “Setting Cookies Example”; 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>” ); } } Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet. <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”

Servlets – Questions and Answers

Servlets – Questions and Answers ”; Previous Next Servlets Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Servlets Interview Questions This section provides a huge collection of Servlets Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Servlets Online Quiz This section provides a great collection of Servlets Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Servlets Online Test If you are preparing to appear for a Java and Servlets Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Servlets Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

Servlets – Sending Email

Servlets – Sending Email ”; Previous Next To send an email using your a Servlet is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. You can download latest version of JavaMail (Version 1.2) from Java”s standard website. You can download latest version of JAF (Version 1.1.1) from Java”s standard website. Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH. Send a Simple Email Here is an example to send a simple email from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. Same time make sure all the jar files from Java Email API package and JAF package are available in CLASSPATH. // File Name SendEmail.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Now set the actual message message.setText(“This is actual message”); // Send message Transport.send(message); String title = “Send Email”; String res = “Sent message successfully….”; 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” + “<p align = “center”>” + res + “</p>n” + “</body> </html>” ); } catch (MessagingException mex) { mex.printStackTrace(); } } } Now let us compile the above servlet and create the following entries in web.xml …. <servlet> <servlet-name>SendEmail</servlet-name> <servlet-class>SendEmail</servlet-class> </servlet> <servlet-mapping> <servlet-name>SendEmail</servlet-name> <url-pattern>/SendEmail</url-pattern> </servlet-mapping> …. Now call this servlet using URL http://localhost:8080/SendEmail which would send an email to given email ID [email protected] and would display following response − Send Email Sent message successfully…. If you want to send an email to multiple recipients then following methods would be used to specify multiple email IDs − void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException Here is the description of the parameters − type − This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO addresses − This is the array of email ID. You would need to use InternetAddress() method while specifying email IDs. Send an HTML Email Here is an example to send an HTML email from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. At the same time, make sure all the jar files from Java Email API package and JAF package are available in CLASSPATH. This example is very similar to previous one, except here we are using setContent() method to set content whose second argument is “text/html” to specify that the HTML content is included in the message. Using this example, you can send as big as HTML content you like. // File Name SendEmail.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(“This is the Subject Line!”); // Send the actual HTML message, as big as you like message.setContent(“<h1>This is actual message</h1>”, “text/html” ); // Send message Transport.send(message); String title = “Send Email”; String res = “Sent message successfully….”; 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” + “<p align = “center”>” + res + “</p>n” + “</body> </html>” ); } catch (MessagingException mex) { mex.printStackTrace(); } } } Compile and run the above servlet to send HTML message on a given email ID. Send Attachment in Email Here is an example to send an email with attachment from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. // File Name SendEmail.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”; // Sender”s email ID needs to be mentioned String from = “[email protected]”; // Assuming you are sending email from localhost String host = “localhost”; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(“mail.smtp.host”, host); // Get the default Session

Servlets – Http Codes

Servlets – Http Status Codes ”; Previous Next The format of the HTTP request and HTTP response messages are similar and will have following structure − An initial status line + CRLF ( Carriage Return + Line Feed i.e. New Line ) Zero or more header lines + CRLF A blank line, i.e., a CRLF An optional message body like file, query data or query output. For example, a server response header looks as follows − HTTP/1.1 200 OK Content-Type: text/html Header2: … … HeaderN: … (Blank Line) <!doctype …> <html> <head>…</head> <body> … </body> </html> The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example). Following is a list of HTTP status codes and associated messages that might be returned from the Web Server − Code Message Description 100 Continue Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request 101 Switching Protocols The server switches protocol. 200 OK The request is OK 201 Created The request is complete, and a new resource is created 202 Accepted The request is accepted for processing, but the processing is not complete. 203 Non-authoritative Information   204 No Content   205 Reset Content   206 Partial Content   300 Multiple Choices A link list. The user can select a link and go to that location. Maximum five addresses 301 Moved Permanently The requested page has moved to a new url 302 Found The requested page has moved temporarily to a new url 303 See Other The requested page can be found under a different url 304 Not Modified   305 Use Proxy   306 Unused This code was used in a previous version. It is no longer used, but the code is reserved 307 Temporary Redirect The requested page has moved temporarily to a new url. 400 Bad Request The server did not understand the request 401 Unauthorized The requested page needs a username and a password 402 Payment Required You cannot use this code yet 403 Forbidden Access is forbidden to the requested page 404 Not Found The server cannot find the requested page. 405 Method Not Allowed The method specified in the request is not allowed. 406 Not Acceptable The server can only generate a response that is not accepted by the client. 407 Proxy Authentication Required You must authenticate with a proxy server before this request can be served. 408 Request Timeout The request took longer than the server was prepared to wait. 409 Conflict The request could not be completed because of a conflict. 410 Gone The requested page is no longer available. 411 Length Required The “Content-Length” is not defined. The server will not accept the request without it. 412 Precondition Failed The precondition given in the request evaluated to false by the server. 413 Request Entity Too Large The server will not accept the request, because the request entity is too large. 414 Request-url Too Long The server will not accept the request, because the url is too long. Occurs when you convert a “post” request to a “get” request with a long query information. 415 Unsupported Media Type The server will not accept the request, because the media type is not supported. 417 Expectation Failed   500 Internal Server Error The request was not completed. The server met an unexpected condition. 501 Not Implemented The request was not completed. The server did not support the functionality required. 502 Bad Gateway The request was not completed. The server received an invalid response from the upstream server. 503 Service Unavailable The request was not completed. The server is temporarily overloading or down. 504 Gateway Timeout The gateway has timed out. 505 HTTP Version Not Supported The server does not support the “http protocol” version. Methods to Set HTTP Status Code The following methods can be used to set HTTP Status Code in your servlet program. These methods are available with HttpServletResponse object. Sr.No. Method & Description 1 public void setStatus ( int statusCode ) This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter. 2 public void sendRedirect(String url) This method generates a 302 response along with a Location header giving the URL of the new document 3 public void sendError(int code, String message) This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client. HTTP Status Code Example Following is the example which would send a 407 error code to the client browser and browser would show you “Need authentication!!!” message. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class showError extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set error code and reason. response.sendError(407, “Need authentication!!!” ); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Now calling the above servlet would display the following result − HTTP Status 407 – Need authentication!!! type Status report messageNeed authentication!!! descriptionThe client must first authenticate itself with the proxy (Need authentication!!!). Apache Tomcat/5.5.29 Print Page Previous Next Advertisements ”;

Servlets – Quick Guide

Servlets – Quick Guide ”; Previous Next Servlets – Overview What are Servlets? Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. 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. Servlets Architecture The following diagram shows the position of Servlets in a Web Application. Servlets Tasks Servlets perform the following major tasks − 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. Servlets Packages Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java”s enterprise edition, an expanded version of the Java class library that supports large-scale development projects. These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1. Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer”s Classpath, you can compile servlets with the JDK”s Java compiler or any other current compiler. What is Next? I would take you step by step to set up your environment to start with Servlets. So fasten your belt for a nice drive with Servlets. I”m sure you are going to enjoy this tutorial very much. Servlets – Environment Setup 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

Servlets – File Uploading

Servlets – File Uploading ”; Previous Next A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a text file or image file or any document. Creating a File Upload Form The following HTM code below creates an uploader form. Following are the important points to be noted down − The form method attribute should be set to POST method and GET method can not be used The form enctype attribute should be set to multipart/form-data. The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file. To upload a single file you should use a single <input …/> tag with attribute type=”file”. To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them. <html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action = “UploadServlet” method = “post” enctype = “multipart/form-data”> <input type = “file” name = “file” size = “50” /> <br /> <input type = “submit” value = “Upload File” /> </form> </body> </html> This will display following result which would allow to select a file from local PC and when user would click at “Upload File”, form would be submitted along with the selected fil − File Upload: Select a file to upload: NOTE: This is just dummy form and would not work. Writing Backend Servlet Following is the servlet UploadServlet which would take care of accepting uploaded file and to store it in directory <Tomcat-installation-directory>/webapps/data. This directory name could also be added using an external configuration such as a context-param element in web.xml as follows − <web-app> …. <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:apache-tomcat-5.5.29webappsdata </param-value> </context-param> …. </web-app> Following is the source code for UploadServlet which can handle multiple file uploading at a time. Before proceeding you have make sure the followings − Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/. FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/. While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded. Make sure you have created directories c:temp and c:apache-tomcat8.0.28webappsdata well in advance. // Import required java libraries import java.io.*; import java.util.*; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.output.*; public class UploadServlet extends HttpServlet { private boolean isMultipart; private String filePath; private int maxFileSize = 50 * 1024; private int maxMemSize = 4 * 1024; private File file ; public void init( ){ // Get the file location where it would be stored. filePath = getServletContext().getInitParameter(“file-upload”); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType(“text/html”); java.io.PrintWriter out = response.getWriter( ); if( !isMultipart ) { out.println(“<html>”); out.println(“<head>”); out.println(“<title>Servlet upload</title>”); out.println(“</head>”); out.println(“<body>”); out.println(“<p>No file uploaded</p>”); out.println(“</body>”); out.println(“</html>”); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(“c:\temp”)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println(“<html>”); out.println(“<head>”); out.println(“<title>Servlet upload</title>”); out.println(“</head>”); out.println(“<body>”); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf(“\”) >= 0 ) { file = new File( filePath + fileName.substring( fileName.lastIndexOf(“\”))) ; } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf(“\”)+1)) ; } fi.write( file ) ; out.println(“Uploaded Filename: ” + fileName + “<br>”); } } out.println(“</body>”); out.println(“</html>”); } catch(Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException(“GET method used with ” + getClass( ).getName( )+”: POST method required.”); } } } Compile and Running Servlet Compile above servlet UploadServlet and create required entry in web.xml file as follows. <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> Now try to upload files using the HTML form which you created above. When you would try http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from your local machine. File Upload: Select a file to upload: If your servlet script works fine, your file should be uploaded in c:apache-tomcat8.0.28webappsdata directory. Print Page Previous Next Advertisements ”;

Servlets – Session Tracking

Servlets – Session Tracking ”; Previous Next HTTP is a “stateless” protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Still there are following three ways to maintain session between web client and web server − Cookies A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie. This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions. Hidden Form Fields A web server can send a hidden HTML form field along with a unique session ID as follows − <input type = “hidden” name = “sessionid” value = “12345”> This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers. This could be an effective way of keeping track of the session but clicking on a regular (<A HREF…>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking. URL Rewriting You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client. URL rewriting is a better way to maintain sessions and it works even when browsers don”t support cookies. The drawback of URL re-writing is that you would have to generate every URL dynamically to assign a session ID, even in case of a simple static HTML page. The HttpSession Object Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below − HttpSession session = request.getSession(); You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object − Sr.No. Method & Description 1 public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. 2 public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. 3 public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 4 public String getId() This method returns a string containing the unique identifier assigned to this session. 5 public long getLastAccessedTime() This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT 6 public int getMaxInactiveInterval() This method returns the maximum time interval (seconds), that the servlet container will keep the session open between client accesses. 7 public void invalidate() This method invalidates this session and unbinds any objects bound to it. 8 public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session. 9 public void removeAttribute(String name) This method removes the object bound with the specified name from this session. 10 public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. 11 public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. Session Tracking Example This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a session object if it is already not created. HttpSession session = request.getSession(true); // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = “Welcome Back to my website”; Integer visitCount = new Integer(0); String visitCountKey = new String(“visitCount”); String userIDKey = new String(“userID”); String userID = new String(“ABCD”); // Check if this is new comer on your web page. if (session.isNew()) { title = “Welcome to my website”; session.setAttribute(userIDKey, userID); } else { visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); // Set response content type response.setContentType(“text/html”); PrintWriter out = response.getWriter(); 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” + “<h2 align = “center”>Session Infomation</h2>n” + “<table border = “1” align = “center”>n” + “<tr bgcolor = “#949494″>n” + ” <th>Session info</th><th>value</th> </tr>n” + “<tr>n” + ” <td>id</td>n” + ” <td>” + session.getId() + “</td> </tr>n” + “<tr>n” + ” <td>Creation Time</td>n” + ” <td>” + createTime + ” </td> </tr>n” + “<tr>n” +

Servlets – Annotations

Servlets – Annotations ”; Previous Next So far, you have learnt how Servlet uses the deployment descriptor (web.xml file) for deploying your application into a web server. Servlet API 3.0 has introduced a new package called javax.servlet.annotation. It provides annotation types which can be used for annotating a servlet class. If you use annotation, then the deployment descriptor (web.xml) is not required. But you should use tomcat7 or any later version of tomcat. Annotations can replace equivalent XML configuration in the web deployment descriptor file (web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the annotated classes at deployment time. The annotation types introduced in Servlet 3.0 are − Sr.No. Annotation & Description 1 @WebServlet To declare a servlet. 2 @WebInitParam To specify an initialization parameter. 3 @WebFilter To declare a servlet filter. 4 @WebListener To declare a WebListener 5 @HandlesTypes To declare the class types that a ServletContainerInitializer can handle. 6 @HttpConstraint This annotation is used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods for which a corresponding HttpMethodConstraint element does NOT occur within the ServletSecurity annotation. 7 @HttpMethodConstraint This annotation is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages. 8 @MultipartConfig Annotation that may be specified on a Servlet class, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type. 9 @ServletSecurity This annotation is used on a Servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol messages. Here we have discussed some of the Annotations in detail. @WebServlet The @WebServlet is used to declare the configuration of a Servlet with a container. The following table contains the list of attributes used for WebServlet annotation. Sr.No. Attribute & Description 1 String name Name of the Servlet 2 String[] value Array of URL patterns 3 String[] urlPatterns Array of URL patterns to which this Filter applies 4 Int loadOnStartup The integer value gives you the startup ordering hint 5 WebInitParam[] initParams Array of initialization parameters for this Servlet 6 Boolean asyncSupported Asynchronous operation supported by this Servlet 7 String smallIcon Small icon for this Servlet, if present 8 String largeIcon Large icon for this Servlet, if present 9 String description Description of this Servlet, if present 10 String displayName Display name of this Servlet, if present At least one URL pattern MUST be declared in either the value or urlPattern attribute of the annotation, but not both. The value attribute is recommended for use when the URL pattern is the only attribute being set, otherwise the urlPattern attribute should be used. Example The following example describes how to use @WebServlet annotation. It is a simple servlet that displays the text Hello Servlet. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value = “/Simple”) public class Simple extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.print(“<html><body>”); out.print(“<h3>Hello Servlet</h3>”); out.print(“</body></html>”); } } Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes. Now try to call any servlet by just running http://localhost:8080/Simple. You will see the following output on the web page. Hello servlet @WebInitParam The @WebInitParam annotation is used for specifying an initialization parameter for a Servlet or a Filter. It is used within a WebFilter or WebSevlet annotations. The following table contains the list of attributes used for WebInitParam annotation. Sr.No. Attribute & Description 1 String name Name of the initialization parameter 2 String value Value of the initialization parameter 3 String description Description of the initialization parameter Example The following example describes how to use @WeInitParam annotation along with @WebServlet annotation. It is a simple servlet that displays the text Hello Servlet and the string value Hello World! which are taken from the init parameters. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value = “/Simple”, initParams = { @WebInitParam(name = “foo”, value = “Hello “), @WebInitParam(name = “bar”, value = ” World!”) }) public class Simple extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.print(“<html><body>”); out.print(“<h3>Hello Servlet</h3>”); out.println(getInitParameter(“foo”)); out.println(getInitParameter(“bar”)); out.print(“</body></html>”); } } Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>;/webapps/ROOT/WEB-INF/classes. Now try to call any servlet by just running http://localhost:8080/Simple. You will see the following output on the web page. Hello Servlet Hello World! @Webfilter This is the annotation used to declare a servlet filter. It is processed by the container at deployment time, and the corresponding filter applied to the specified URL patterns, servlets, and dispatcher types. The @WebFilter annotation defines a filter in a web application. This annotation is specified on a class and contains metadata about the filter being declared. The annotated filter must specify at least one URL pattern. The following table lists the attributes used for WebFilter annotation. Sr.No. Attribute & Description 1 String filterName Name of the filter 2 String[] urlPatterns Provides array of values or urlPatterns to which the filter applies 3 DispatcherType[] dispatcherTypes Specifies the types of dispatcher (Request/Response) to which the filter applies 4 String[] servletNames Provides an array of servlet names 5 String displayName Name of the filter 6 String description Description of the filter 7 WebInitParam[] initParams Array of initialization parameters for this filter 8 Boolean asyncSupported Asynchronous operation supported by this filter 9 String smallIcon Small icon for this filter, if present 10 String largeIcon Large icon for this filter, if present Example The following example describes how to use @WebFilter annotation. It is a simple LogFilter that displays the value of Init-param test-param and the current time timestamp on the console. That means, the filter works like an interface layer between the request and the response. Here we use “/*” for

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