Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
SERVLETSTUTORIAL
tutorialspoint.com
i
Servlets Tutorial
Servlets provide a component-based, platform-independent method for building Web-based 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.
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 Servelts 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.
Table of Content
Servlets Tutorial ....................................................................... 2 Audience .................................................................................. 2 Prerequisites ............................................................................ 2 Copyright & Disclaimer Notice .................................................. 2 Overview .................................................................................. 7
Servlets Architecture: ................................................................................ 7 Servlets Tasks: .......................................................................................... 8 Servlets Packages: .................................................................................... 8 What is Next? ............................................................................................ 8
Environment ............................................................................. 9
Setting up Java Development Kit............................................................... 9 Setting up Web Server: Tomcat............................................................... 10 Setting up CLASSPATH .......................................................................... 11
Examples ............................................................................... 15
Sample Code for Hello World: ................................................................. 15 Compiling a Servlet: ................................................................................ 16 Servlet Deployment: ................................................................................ 16
Session Tracking.................................................................... 54
Cookies: .................................................................................................. 54 Hidden Form Fields: ................................................................................ 54 URL Rewriting: ........................................................................................ 54 The HttpSession Object: .......................................................................... 55 TUTORIALS POINT Simply Easy Learning
Display Current Date & Time .................................................. 69 Mon Jun 21 21:46:49 GMT+04:00 2010 ................................. 69
Date Comparison:.................................................................................... 70 Date Formatting using SimpleDateFormat: ............................................. 70
Send Email............................................................................. 82
Send an HTML Email: ............................................................................. 82 Send Attachment in Email: ...................................................................... 83 User Authentication Part: ......................................................................... 85
Packaging .............................................................................. 86
Creating Servlets in Packages:................................................................ 86 Compiling Servlets in Packages: ............................................................. 87 Packaged Servlet Deployment: ............................................................... 87
Internationalization ................................................................. 92
Detecting Locale: ..................................................................................... 92 Example: ................................................................................................. 93 Languages Setting: .................................................................................. 93 Locale Specific Dates: ............................................................................. 94 Locale Specific Currency ......................................................................... 95 Locale Specific Percentage ..................................................................... 95
CHAPTER
Overview
What are Servlets?
ava Servlets are programs that run on a Web or Application server and act as a middle layer between a
request 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:
Following diagram shows the position of Servelts 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.
CHAPTER
Environment
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 following steps:
Download latest version of Tomcat from http://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in
C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on windows machine: %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.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-5.5.29/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: on Linux/Unix and create
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-5.5.29\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine: /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up 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-5.5.29 set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH% 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 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-5.5.29 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.
CHAPTER
Life Cycle
servlet life cycle can be defined as the entire process from its creation till the destruction. The following
The servlet is initialized by calling the init () method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the signature of this method: publicvoid service(ServletRequest request, ServletResponse response) throwsServletException,IOException{ } The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client. The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container. The servlet container loads the servlet before invoking the service() method. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
CHAPTER
Examples
ervlets are Java classes which service HTTP requests and implement the javax.servlet.Servletinterface.
Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH. Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows: $ javac HelloWorld.java 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. This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable. If everything goes fine, above compilation would produce HelloWorld.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 <Tomcat-installation-directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes. If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEBINF/classes/com/myorg/MyServlet.class. For now, let us copy HelloWorld.class into <Tomcat-installation-directory>/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>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There could be various entries in this table already available, but never mind. You are almost done, now let us start tomcat server using <Tomcat-installation-directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address box. If everything goes fine, you would get following result:
CHAPTER
Form Data
ou 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 ? character as follows: http://www.test.com/hello?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. 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 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.
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.
</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:
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.
throwsServletException,IOException { // Set response content type response.setContentType("text/html"); PrintWriterout= 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. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } Now compile, deploy the above Servlet and test it using Hello.htm with the POST method as follows: <html> <body> <formaction="HelloForm"method="POST"> First Name: <inputtype="text"name="first_name"> <br/> Last Name: <inputtype="text"name="last_name"/> <inputtype="submit"value="Submit"/> </form> </body> </html> Here is the actual output of the above form, Try to enter First 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 would generate similar result as mentioned in the above examples.
Below is CheckBox.java servlet program to handle input given by web browser for checkbox button. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class publicclassCheckBoxextendsHttpServlet{ // Method to handle GET method request. publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); String title ="Reading Checkbox 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>Maths Flag : </b>: " + request.getParameter("maths")+"\n"+ " <li><b>Physics Flag: </b>: " + request.getParameter("physics")+"\n"+ " <li><b>Chemistry Flag: </b>: " + request.getParameter("chemistry")+"\n"+
"</ul>\n"+ "</body></html>"); } // Method to handle POST method request. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } For the above example, it would display following result:
"<th>Param Name</th><th>Param Value(s)</th>\n"+ "</tr>\n"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()){ String paramName =(String)paramNames.nextElement(); out.print("<tr><td>"+ paramName +"</td>\n<td>"); String[] paramValues = request.getParameterValues(paramName); // Read single valued data if(paramValues.length ==1){ String paramValue = paramValues[0]; if(paramValue.length()==0) out.println("<i>No Value</i>"); else out.println(paramValue); }else{ // Read multiple valued data out.println("<ul>"); for(int i=0; i < paramValues.length; i++){ out.println("<li>"+ paramValues[i]); } out.println("</ul>"); } } out.println("</tr>\n</table>\n</body></html>"); } // Method to handle POST method request. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } Now, try above servlet with the following form: <html> <body> <formaction="ReadParams"method="POST"target="_blank"> <inputtype="checkbox"name="maths"checked="checked"/> Maths <inputtype="checkbox"name="physics"/> Physics <inputtype="checkbox"name="chemistry"checked="checked"/> Chem <inputtype="submit"value="Select Subject"/> </form> </body> </html> Now calling servlet using above form would generate following result:
You can try above servlet to read any other form's data which is having other objects like text box, radio button or drop down box etc.
CHAPTER
Client Request
W
Header Accept
hen a browser requests for a web page, it sends lot of information to the web server which can not be
read directly because this information travel as a part of header of HTTP request. You can check HTTP Protocol for more information on this. Following is the important header information which comes from browser side and you would use very frequently in web programming: Description This header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities. This header specifies the character sets the browser can use to display the information. For example ISO-8859-1. This header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities. This header specifies the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc. This header is used by clients to identify themselves when accessing password-protected Web pages. This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used This header is applicable only to POST requests and gives the size of the POST data in bytes. This header returns cookies to servers that previously sent them to the browser. This header specifies the host and port as given in the original URL. This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available.
Accept-Charset
Accept-Encoding
Accept-Language
Authorization
Connection
If-Unmodified-Since
This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date. This header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2. This header identifies the browser or other client making the request and can be used to return different content to different types of browsers.
Referer
User-Agent
8 9
10
11 12 13
Returns the portion of the request URI that indicates the context of the request. 14 String getHeader(String name) Returns the value of the specified request header as a String. String getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. String getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. String getPathInfo() Returns any extra path information associated with the URL the client sent when it made this request. String getProtocol() Returns the name and version of the protocol the request. String getQueryString() Returns the query string that is contained in the request URL after the path. String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent the request. String getRemoteHost() Returns the fully qualified name of the client that sent the request. String getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. String getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. String getRequestedSessionId() Returns the session ID specified by the client. String getServletPath() Returns the part of this request's URL that calls the JSP. String[] getParameterValues(String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. boolean isSecure() Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS. int getContentLength() Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. int getIntHeader(String name) Returns the value of the specified request header as an int. int getServerPort() Returns the port number on which this request was received.
15
16 17 18 19 20 21
22
23
24 25
26
27
28
29 30
CHAPTER
Server Response
s discussed in previous chapter, when a Web server responds to a HTTP request to the browser, the
response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this: HTTP/1.1200 OK Content-Type: text/html Header2:... ... HeaderN:... (BlankLine) <!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 summary of the most useful HTTP 1.1 response headers which go back to the browser from web server side and you would use them very frequently in web programming: Header Allow Description This header specifies the request methods (GET, POST, etc.) that the server supports. This header specifies the circumstances in which the response document can safely be cached. It can have values public, private orno-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (nonshared) caches and no-cache means document should never be cached. This header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keep-alive means using persistent connections.
Cache-Control
Connection
This header lets you request that the browser ask the user to save the response to disk in a file of the given name. This header specifies the way in which the page was encoded during transmission. This header signifies the language in which the document is written. For example en, en-us, ru, etc. This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. This header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. This header specifies the time at which the content should be considered out-ofdate and thus no longer be cached. This header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests. This header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. This header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed. This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. This header specifies a cookie associated with the page.
Last-Modified
Location
3 4 5 6 7
8 9 10 11 12 13 14 15
void addIntHeader(String name, int value) Adds a response header with the given name and integer value. void flushBuffer() Forces any content in the buffer to be written to the client. void reset() Clears any data that exists in the buffer as well as the status code and headers. void resetBuffer() Clears the content of the underlying buffer in the response without clearing headers or status code. void sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer. void sendError(int sc, String msg) Sends an error response to the client using the specified status. void sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL. void setBufferSize(int size) Sets the preferred buffer size for the body of the response. void setCharacterEncoding(String charset) Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF8. void setContentLength(int len) Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header. void setContentType(String type) Sets the content type of the response being sent to the client, if the response has not been committed yet. void setDateHeader(String name, long date) Sets a response header with the given name and date-value. void setHeader(String name, String value) Sets a response header with the given name and value. void setIntHeader(String name, int value) Sets a response header with the given name and integer value. void setLocale(Locale loc) Sets the locale of the response, if the response has not been committed yet. void setStatus(int sc) Sets the status code for this response.
16
17
18
19 20 21 22 23
// Extend HttpServlet class publicclassRefreshextendsHttpServlet{ // Method to handle GET method request. publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh",5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar =newGregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM)==0) am_pm ="AM"; else am_pm ="PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriterout= response.getWriter(); String title ="Auto Refresh Header Setting"; 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>Current Time is: "+ CT +"</p>\n"); } // Method to handle POST method request. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } Now calling the above servlet would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result:
CHAPTER
Http Codes
he 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 ie. New Line ) Zero or more header lines + CRLF A blank line ie. a CRLF An optioanl message body like file, query data or query output.
For example, a server response header looks as follows: HTTP/1.1200 OK Content-Type: text/html Header2:... ... HeaderN:... (BlankLine) <!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: 100 101 200 Continue Switching Protocols OK Description: 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 The server switches protocol. The request is OK
201 202 203 204 205 206 300 301 302 303 304 305 306 307 400 401 402 403 404 405 406 407 408 409 410 411 412 413
Created Accepted Non-authoritative Information No Content Reset Content Partial Content Multiple Choices Moved Permanently Found See Other Not Modified Use Proxy Unused Temporary Redirect Bad Request Unauthorized Payment Required Forbidden Not Found Method Not Allowed Not Acceptable Proxy Authentication Required Request Timeout Conflict Gone Length Required Precondition Failed Request Entity Too Large
The request is complete, and a new resource is created The request is accepted for processing, but the processing is not complete.
A link list. The user can select a link and go to that location. Maximum five addresses The requested page has moved to a new url The requested page has moved temporarily to a new url The requested page can be found under a different url
This code was used in a previous version. It is no longer used, but the code is reserved. The requested page has moved temporarily to a new url. The server did not understand the request The requested page needs a username and a password You can not use this code yet Access is forbidden to the requested page The server can not find the requested page. The method specified in the request is not allowed. The server can only generate a response that is not accepted by the client. You must authenticate with a proxy server before this request can be served. The request took longer than the server was prepared to wait. The request could not be completed because of a conflict. The requested page is no longer available. The "Content-Length" is not defined. The server will not accept the request without it. The precondition given in the request evaluated to false by the server. The server will not accept the request, because the request entity is too large.
414 Request-url Too Long 415 417 500 501 502 503 504 505
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. The server will not accept the request, because the media type is not supported.
Unsupported Media Type Expectation Failed Internal Server Error Not Implemented Bad Gateway Service Unavailable Gateway Timeout HTTP Version Not Supported
The request was not completed. The server met an unexpected condition The request was not completed. The server did not support the functionality required. The request was not completed. The server received an invalid response from the upstream server The request was not completed. The server is temporarily overloading or down. The gateway has timed out. The server does not support the "http protocol" version.
publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set error code and reason. response.sendError(407,"Need authentication!!!"); } // Method to handle POST method request. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } Now calling the above servlet would display following result:
APACHE TOMCAT/5.5.29
CHAPTER
Writing Filters
ervlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end. To manipulate responses from server before they are sent back to the client.
There are are various types of filters suggested by the specifications: Authentication Filters. Data compression Filters. Encryption Filters. Filters that trigger resource access events. Image Conversion Filters. Logging and Auditing Filters. MIME-TYPE Chain Filters. Tokenizing Filters XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor. When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
S.N. Method & Description 1 public void doFilter (ServletRequest, ServletResponse, FilterChain) This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. public void init(FilterConfig filterConfig) This method is called by the web container to indicate to a filter that it is being placed into service. public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service.
10
Exception Handling
CHAPTER
hen a servlet throws an exception, the web container searches the configurations in web.xml that use
the exception-type element for a match with the thrown exception type. You would have to use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.
web.xml Configuration:
Consider you have an ErrorHandler servelt which would be called whenever there is any defined exception or error. Following would be the entry created in web.xml. <!-- servlet definition --> <servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet mappings --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <!-- error-code related error pages --> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <error-code>403</error-code> <location>/ErrorHandler</location> </error-page> <!-- exception-type related error pages --> <error-page> <exception-type> javax.servlet.ServletException </exception-type> <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/ErrorHandler</location>
</error-page> If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception: <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/ErrorHandler</location> </error-page> Following are the points to be noted about above web.xml for Exception Handling:
The servelt ErrorHandler is defined in usual way as any other servlet and configured in web.xml. If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then ErrorHandler servlet would be called. If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet. You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept.
out.println("Servlet Name : "+ servletName + "</br></br>"); out.println("Exception Type : "+ throwable.getClass().getName()+ "</br></br>"); out.println("The request URI: "+ requestUri + "<br><br>"); out.println("The exception message: "+ throwable.getMessage()); } out.println("</body>"); out.println("</html>"); } // Method to handle POST method request. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } Compile ErrorHandler.java in usual way directory>/webapps/ROOT/WEB-INF/classes. and put your class file in <Tomcat-installation-
Let us add the following configuration in web.xml to handle exceptions: <servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet mappings --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/ErrorHandler</location> </error-page> Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to call ErrorHandler servlet and display an appropriate message as programmed. For example, if you type a wrong URL then it would display the following result: The status code :404 Above code may not work with some web browsers. So try with Mozilla and Safari and it should work.
11
Cookies Handling
CHAPTER
ookies 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.
User-Agent:Mozilla/4.6(X11; I;Linux2.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.
5 6 7
10
11
12
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 publicclassHelloFormextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Create cookies for first and last names. Cookie firstName =newCookie("first_name", request.getParameter("first_name")); Cookie lastName =newCookie("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"); PrintWriterout= 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 above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet.
<html> <body> <formaction="HelloForm"method="GET"> First Name: <inputtype="text"name="first_name"> <br/> Last Name: <inputtype="text"name="last_name"/> <inputtype="submit"value="Submit"/> </form> </body> </html>
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button. Next section would explain you how you would access these cookies back in your web application.
Example:
Let us read cookies which we have set in previous example:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class publicclassReadCookiesextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { Cookie cookie =null; Cookie[] cookies =null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); String title ="Reading 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"); if( cookies !=null){ out.println("<h2> Found Cookies Name and Value</h2>"); for(int i =0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : "+ cookie.getName()+", "); out.print("Value: "+ cookie.getValue()+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } } Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then running http://localhost:8080/ReadCookies would display the following result:
Read an already exsiting cookie and store it in Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie. Add this cookie back into response header.
Example:
Following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class publicclassDeleteCookiesextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { Cookie cookie =null; Cookie[] cookies =null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); String title ="Delete 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"); if( cookies !=null){ out.println("<h2> Cookies Name and Value</h2>"); for(int i =0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName()).compareTo("first_name")==0){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie : "+ cookie.getName()+"<br/>"); } out.print("Name : "+ cookie.getName()+", "); out.print("Value: "+ cookie.getValue()+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); }
} Compile above servlet DeleteCookies and create appropriate entry runninghttp://localhost:8080/DeleteCookies would display the following result: in web.xml file. Now
12
Session Tracking
CHAPTER
TTP 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.
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 works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
9 10
11
" <td>id</td>\n"+ " <td>"+ session.getId()+"</td></tr>\n"+ "<tr>\n"+ " <td>Creation Time</td>\n"+ " <td>"+ createTime + " </td></tr>\n"+ "<tr>\n"+ " <td>Time of Last Access</td>\n"+ " <td>"+ lastAccessTime + " </td></tr>\n"+ "<tr>\n"+ " <td>User ID</td>\n"+ " <td>"+ userID + " </td></tr>\n"+ "<tr>\n"+ " <td>Number of visits</td>\n"+ " <td>"+ visitCount +"</td></tr>\n"+ "</table>\n"+ "</body></html>"); } } Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now runninghttp://localhost:8080/SessionTrack would display the following result when you would run for the first time:
Welcome to my website
Session Infomation
Session info Id Creation Time Time of Last Access User ID Number of visits Value 0AE3EC93FF44E3C525B4351B77ABB2D5 Tue Jun 08 17:26:40 GMT+04:00 2010 Tue Jun 08 17:26:40 GMT+04:00 2010 ABCD 0
Now try to run the same servlet for second time, it would display following result.
Session Infomation
info type Id Creation Time Time of Last Access User ID Number of visits value 0AE3EC93FF44E3C525B4351B77ABB2D5 Tue Jun 08 17:26:40 GMT+04:00 2010 Tue Jun 08 17:26:40 GMT+04:00 2010 ABCD 1
Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session: You can call public void invalidate() method to discard an entire session. Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users. web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.
<session-config> <session-timeout>15</session-timeout> </session-config> The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat. The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.
13
Database Access
CHAPTER
his tutorial assumes you have understanding on how JDBC application works. Before starting with
database access through a servlet, make sure you have proper JDBC environment setup along with a database. For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial. To start with basic concept, let us create a simple table and create few records in that table as follows:
Create Table
To create the Employees table in TEST database, use the following steps:
Step 1:
Open a Command Prompt and change to the installation directory as follows: C:\> C:\>cd ProgramFiles\MySQL\bin C:\Program Files\MySQL\bin>
Step 2:
Login to database as follows C:\Program Files\MySQL\bin>mysql -u root -p Enter password:******** mysql>
Step 3:
Create the table Employee in TEST database as follows: mysql>use TEST; mysql> create table Employees ( id intnotnull, age intnotnull, first varchar (255),
last varchar (255) ); Query OK,0 rows affected (0.08 sec) mysql>
Accessing a Database:
Here is an example which shows how to access TEST database using Servlet. // Loading required libraries import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; publicclassDatabaseAccessextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // JDBC driver name and database URL staticfinalString JDBC_DRIVER="com.mysql.jdbc.Driver"; staticfinalString DB_URL="jdbc:mysql://localhost/TEST"; // Database credentials staticfinalString USER ="root"; staticfinalString PASS ="password"; // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); String title ="Database Result"; 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"); try{ // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection conn =DriverManager.getConnection(DB_URL,USER,PASS); // Execute SQL query stmt = conn.createStatement(); String sql; sql ="SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); // Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); Stringlast= rs.getString("last"); //Display values out.println("ID: "+ id +"<br>"); out.println(", Age: "+ age +"<br>"); out.println(", First: "+ first +"<br>"); out.println(", Last: "+last+"<br>"); } out.println("</body></html>"); // Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try } } Now let us compile above servlet and create following entries in web.xml .... <servlet>
<servlet-name>DatabaseAccess</servlet-name> <servlet-class>DatabaseAccess</servlet-class> </servlet> <servlet-mapping> <servlet-name>DatabaseAccess</servlet-name> <url-pattern>/DatabaseAccess</url-pattern> </servlet-mapping> .... Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display following response:
DatabaseResult
ID:100,Age:18,First:Zara,Last:Ali ID:101,Age:25,First:Mahnaz,Last:Fatma ID:102,Age:30,First:Zaid,Last:Khan ID:103,Age:28,First:Sumit,Last:Mittal
14
File Uploading
CHAPTER
Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file
<html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br/> <formaction="UploadServlet"method="post" enctype="multipart/form-data"> <inputtype="file"name="file"size="50"/> <br/> <inputtype="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 file:
Following example depends on FileUpload, so make sure you have the latest version ofcommonsfileupload.x.x.jar file in your classpath. You can download it fromhttp://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 http://commons.apache.org/io/. While testing following example, you should upload a file which has less size than maxFileSizeotherwise file would not be uploaded. Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well in advance.
import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.output.*; publicclassUploadServletextendsHttpServlet{ privateboolean isMultipart; privateString filePath; privateint maxFileSize =50*1024; privateint maxMemSize =4*1024; privateFile file ; publicvoid init(){
if(!fi.isFormField ()) {
If your servlet script works fine, your file should be uploaded in c:\apache-tomcat-5.5.29\webapps\data\ directory.
15
Handling Date
CHAPTER
O
Date()
ne of the most important advantages of using Servlet is that you can use most of the methods available in
core Java. This tutorial would take you through Java provided Date class which is available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors. The first constructor initializes the object with the current date and time.
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970 Date(long millisec) Once you have a Date object available, you can call any of the following support methods to play with dates: SN Methods with Description 1 boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. Object clone( ) Duplicates the invoking Date object. int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
7 8
long getTime( ) Returns the number of milliseconds that have elapsed since January 1, 1970. int hashCode( ) Returns a hash code for the invoking object. void setTime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970 String toString( ) Converts the invoking Date object into a string and returns the result.
10
Date Comparison:
As I mentioned above you can use all the available Java methods in your Servlet. In case you need to compare two dates, following are the methods:
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result:
For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation.
16
Page Redirect
CHAPTER
age redirection is generally used when a document moves to a new location and we need to send the client
to this new location or may be because of load balancing, or for simple randomization. The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the signature of this method: publicvoidHttpServletResponse.sendRedirect(String location) throwsIOException This method sends back the response to the browser along with the status code and new page location. You can also use setStatus() and setHeader() methods together to achieve the same: .... String site ="http://www.newpage.com"; response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); ....
Example:
This example shows how a servlet performs page redirection to another location: import import import import import java.io.*; java.sql.Date; java.util.*; javax.servlet.*; javax.servlet.http.*;
publicclassPageRedirectextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); // New location to be redirected String site =newString("http://www.photofuntoos.com"); response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); } } Now let us compile above servlet and create following entries in web.xml .... <servlet> <servlet-name>PageRedirect</servlet-name> <servlet-class>PageRedirect</servlet-class> </servlet> <servlet-mapping> <servlet-name>PageRedirect</servlet-name> <url-pattern>/PageRedirect</url-pattern> </servlet-mapping> .... Now call this servlet using URL http://localhost:8080/PageRedirect. This would take you given URL http://www.photofuntoos.com.
17
Hits Counter
Hit Counter for a Web Page
CHAPTER
any times you would be interested in knowing total number of hits on a particular page of your
website. It is very simple to count these hits using a servlet because the life cycle of a servlet is controlled by the container in which it runs. Following are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle: Initialize a global variable in init() method. Increase global variable every time either doGet() or doPost() method is called. If required, you can use a database table to store the value of global variable in destroy() method. This value can be read inside init() method when servlet would be initialized next time. This step is optional. If you want to count only unique page hits with-in a session then you can use isNew() method to check if same page already have been hit with-in that session. This step is optional. You can display value of the global counter to show total number of hits on your web site. This step is also optional.
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
Example:
This example shows how to implement a simple page hit counter: import import import import import java.io.*; java.sql.Date; java.util.*; javax.servlet.*; javax.servlet.http.*;
publicvoid init() { // Reset hit counter. hitCount =0; } publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); // This method executes whenever the servlet is hit // increment hitCount hitCount++; PrintWriterout= response.getWriter(); String title ="Total Number of Hits"; 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\">"+ hitCount +"</h2>\n"+ "</body></html>"); } publicvoid destroy() { // This is optional step but if you like you // can write hitCount value in your database. } } Now let us compile above servlet and create following entries in web.xml .... <servlet> <servlet-name>PageHitCounter</servlet-name> <servlet-class>PageHitCounter</servlet-class> </servlet> <servlet-mapping> <servlet-name>PageHitCounter</servlet-name> <url-pattern>/PageHitCounter</url-pattern> </servlet-mapping> .... Now call this servlet using URL http://localhost:8080/PageHitCounter. This would increase counter by one every time this page gets refreshed and it would display following result:
Initialize a global variable in init() method of a filter. Increase global variable every time doFilter method is called. If required, you can use a database table to store the value of global variable in destroy() method of filter. This value can be read inside init() method when filter would be initialized next time. This step is optional.
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
Example:
This example shows how to implement a simple website hit counter: // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; publicclassSiteHitCounterimplementsFilter{ privateint hitCount; publicvoid init(FilterConfig config) throwsServletException{ // Reset hit counter. hitCount =0; } publicvoid doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException,ServletException{ // increase counter by one hitCount++; // Print the counter. System.out.println("Site visits count :"+ hitCount ); // Pass request back down the filter chain chain.doFilter(request,response); } publicvoid destroy() {
// This is optional step but if you like you // can write hitCount value in your database. } } Now let us compile above servlet and create following entries in web.xml .... <filter> <filter-name>SiteHitCounter</filter-name> <filter-class>SiteHitCounter</filter-class> </filter> <filter-mapping> <filter-name>SiteHitCounter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> .... Now call any URL like URL http://localhost:8080/. This would increase counter by one every time any page gets a hit and it would display following message in the log: Site visits count :1 Site visits count :2 Site visits count :3 Site visits count :4 Site visits count :5 ..................
18
Auto Refresh
CHAPTER
onsider a webpage which is displaying live game score or stock market status or currency exchange
ration. For all such type of pages, you would need to refresh your web page regularly using referesh or reload button with your browser. Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval. The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method: publicvoid setIntHeader(String header,int headerValue) This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
Calendar calendar =newGregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM)==0) am_pm ="AM"; else am_pm ="PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriterout= response.getWriter(); String title ="Auto Page Refresh using Servlet"; 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>Current Time is: "+ CT +"</p>\n"); } // Method to handle POST method request. publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{ doGet(request, response); } } Now let us compile above servlet and create following entries in web.xml .... <servlet> <servlet-name>Refresh</servlet-name> <servlet-class>Refresh</servlet-class> </servlet> <servlet-mapping> <servlet-name>Refresh</servlet-name> <url-pattern>/Refresh</url-pattern> </servlet-mapping> .... Now call this servlet using URL http://localhost:8080/Refresh which would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result:
19
Sending Email
CHAPTER
o send an email using your a Servlet is simple enough but to start with you should have JavaMail
APIand 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.
// 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"); PrintWriterout= response.getWriter(); try{ // Create a default MimeMessage object. MimeMessage message =newMimeMessage(session); // Set From: header field of the header. message.setFrom(newInternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, newInternetAddress(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 above servlet and create 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 abcd@gmail.com 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) throwsMessagingException 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
// Get the default Session object. Session session =Session.getDefaultInstance(properties); // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); try{ // Create a default MimeMessage object. MimeMessage message =newMimeMessage(session); // Set From: header field of the header. message.setFrom(newInternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, newInternetAddress(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 above servlet to send HTML message on a given email ID.
publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Recipient's email ID needs to be mentioned. String to ="abcd@gmail.com"; // Sender's email ID needs to be mentioned Stringfrom="web@gmail.com"; // 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"); PrintWriterout= response.getWriter(); try{ // Create a default MimeMessage object. MimeMessage message =newMimeMessage(session); // Set From: header field of the header. message.setFrom(newInternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, newInternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Create the message part BodyPart messageBodyPart =newMimeBodyPart(); // Fill the message messageBodyPart.setText("This is message body"); // Create a multipar message Multipart multipart =newMimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart =newMimeBodyPart(); String filename ="file.txt"; DataSource source =newFileDataSource(filename); messageBodyPart.setDataHandler(newDataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts
message.setContent(multipart ); // 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 above servlet to send a file as an attachement along with a message on a given email ID.
20
Packaging
CHAPTER
he web application structure involving the WEB-INF subdirectory is standard to all Java web applications
and specified by the servlet API specification. Given a top-level directory name of myapp, Here is what this directory structure looks like: /myapp /images /WEB-INF /classes /lib The WEB-INF subdirectory contains the application's deployment descriptor, named web.xml. All the HTML files live in the top-level directory which is myapp. For admin user, you would find ROOT directory as parent directory as myapp.
publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriterout= response.getWriter(); out.println("<h1>"+ message +"</h1>"); } publicvoid destroy() { // do nothing. } }
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There could be various entries in this table already available, but never mind. You are almost done, now let us start tomcat server using <Tomcat-installation-directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/MyServlet in browser's address box. If everything goes fine, you would get following result:
Hello World
21
Debugging
CHAPTER
tisalways difficult to testing/debugging a servlets. Servlets tend to involve a large amount of client/server
interaction, making errors likely but hard to reproduce. Here are a few hints and suggestions that may aid you in your debugging.
System.out.println()
System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Additionally: Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications. Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial.
Following is the syntax to use System.out.println(): System.out.println("Debugging message"); All the messages generated by above syntax would be logged in web server log file.
Message Logging:
It is always great idea to use proper logging method to log all the debug, warning and error messages using a standard logging method. I use log4J to log all the messages. The Servlet API also provides a simple way of outputting information by using the log() method as follows: // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publicclassContextLogextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response)throwsServletException,
java.io.IOException{ String par = request.getParameter("par1"); //Call the two ServletContext.log methods ServletContext context = getServletContext(); if(par ==null|| par.equals("")) //log version with Throwable parameter context.log("No message received:", newIllegalStateException("Missing parameter")); else context.log("Here is the visitor's message: "+ par); response.setContentType("text/html"); java.io.PrintWriterout= response.getWriter(); String title ="Context Log"; 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\">Messages sent</h2>\n"+ "</body></html>"); }//doGet } The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in <Tomcat-installation-directory>/logs. The log files do give an indication of new emerging bugs or the frequency of problems. For that reason it's good to use the log() function in the catch clause of exceptions which should normally not occur.
Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes. Set your debugger's classpath so that it can also find your servlets and support classes, typically server_root/servlets and server_root/classes.
You normally wouldn't want server_root/servlets in your classpath because it disables servlet reloading. This inclusion, however, is useful for debugging. It allows your debugger to set breakpoints in a servlet before the custom servlet loader in HttpServer loads the servlet. Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever servlet you're interested in debugging, then use a web browser to make a request to the HttpServer for
the given servlet (http://localhost:8080/servlet/ServletToDebug). You should see execution stop at your breakpoints.
Using Comments:
Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process. The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem.
Be aware that server_root/classes doesn't reload and that server_root/servlets probably does. Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu. Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh. Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away.
22
Internationalization
CHAPTER
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 it to a particular geographical or cultural region for example Hindi translation to a web site. 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 ie. 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. S.N. Method & Description 1 2 3 4 5 String getCountry() This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format. String getDisplayCountry() This method returns a name for the locale's country that is appropriate for display to the user. String getLanguage() This method returns the language code in lower case for this locale in ISO 639 format. String getDisplayLanguage() This method returns a name for the locale's language that is appropriate for display to the user. 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 import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.util.Locale;
publicclassGetLocaleextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,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"); PrintWriterout= 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 Content-Language header to display all the characters properly. Second point is to display all the special characters using HTML entities, For example, "ñ" represents "", and "¡" represents "" as follows: import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.util.Locale;
HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); // Set spanish language code. response.setHeader("Content-Language","es"); String title ="En Españ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ñol:"+"</h1>\n"+ "<h1>"+"¡Hola Mundo!"+"</h1>\n"+ "</body></html>"); } }
publicclassDateLocaleextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); PrintWriterout= response.getWriter(); //Get the client's Locale Locale locale = request.getLocale(); String date =DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.SHORT, locale).format(newDate()); 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>"); } }
publicclassCurrencyLocaleextendsHttpServlet{ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); PrintWriterout= 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>"); } }
publicclassPercentageLocaleextendsHttpServlet{
publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException { // Set response content type response.setContentType("text/html"); PrintWriterout= 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 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\">"+ formattedPerc +"</h1>\n"+ "</body></html>"); } }