Servlets – Writing Filters

Servlets – Writing Filters ”; Previous Next Servlet 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 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. Servlet Filter Methods A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods − Sr.No. 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. 2 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. 3 public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service. Servlet Filter − Example Following is the Servlet Filter Example that would print the clients IP address and current date time. This example would give you basic understanding of Servlet Filter, but you can write more sophisticated filter applications using the same concept − // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException { // Get init parameter String testParam = config.getInitParameter(“test-param”); //Print the init parameter System.out.println(“Test Param: ” + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println(“IP “+ ipAddress + “, Time ” + new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ) { /* Called before the Filter instance is removed from service by the web container*/ } } Compile LogFilter.java in usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes Servlet Filter Mapping in Web.xml Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined and then mapped to a URL pattern. Create the following entry for filter tag in the deployment descriptor file web.xml <filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The above filter would apply to all the servlets because we specified /* in our configuration. You can specicy a particular servlet path if you want to apply filter on few servlets only. Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J logger to log above log in a separate file. Using Multiple Filters Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below − <filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>AuthenFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Filters Application Order The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file. For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet but the following example would reverse the order − <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Print Page Previous Next Advertisements ”;

Servlets – Useful Resources

Servlets – Useful Resources ”; Previous Next The following resources contain additional information on Servlets. Please use them to get more in-depth knowledge on this topic. Java Servlet Online Training 20 Lectures 5 hours Tutorialspoint More Detail Complete Java Course – Core Java, JSP & Servlets Most Popular 241 Lectures 30 hours Anand Mahajan More Detail JSP, Servlet, JSLT + Hibernate: A Complete Course 109 Lectures 11 hours Chaand Sheikh More Detail Print Page Previous Next Advertisements ”;

Servlets – Discussion

Discuss Servlets ”; Previous Next Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. Print Page Previous Next Advertisements ”;

Servlets – Packaging

Servlets – Packaging ”; Previous Next The 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 how 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 should be kept in the top-level directory which is myapp. For admin user, you would find ROOT directory as parent directory. Creating Servlets in Packages The WEB-INF/classes directory contains all the servlet classes and other class files, in a structure that matches their package name. For example, If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in the following directory − /myapp/WEB-INF/classes/com/myorg/MyServlet.class Following is the example to create MyServlet class with a package name com.myorg // Name your package package com.myorg; // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = “Hello World”; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println(“<h1>” + message + “</h1>”); } public void destroy() { // do nothing. } } Compiling Servlets in Packages There is nothing much different to compile a class available in package. The simplest way is to keep your java file in fully qualified path, as mentioned above class would be kept in com.myorg. You would also need to add this directory in CLASSPATH. Assuming your environment is setup properly, go in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes directory and compile MyServlet.java as follows $ javac MyServlet.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 MyServlet.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production. Packaged Servlet Deployment By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-installationdirectory>/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 WEB-INF/classes/com/myorg/MyServlet.class and you would need to create following entries in web.xml file located in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/ <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.myorg.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</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-installationdirectory>binstartup.bat (on windows) or <Tomcat-installationdirectory>/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 Print Page Previous Next Advertisements ”;

Servlets – Auto Refresh

Servlets – Auto Page Refresh ”; Previous Next Consider 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 refresh 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 − public void 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. Auto Page Refresh Example This example shows how a servlet performs auto page refresh using setIntHeader() method to set Refresh header. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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 = new GregorianCalendar(); 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; PrintWriter out = 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. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Now let us compile the above servlet and create the 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 − Auto Page Refresh using Servlet Current Time is: 9:44:50 PM Print Page Previous Next Advertisements ”;

Servlets – Debugging

Servlets – Debugging ”; Previous Next It is always 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. Stopping at breakpoints technique stops the normal execution hence takes more time. Whereas 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.*; public class ContextLog extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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:”, new IllegalStateException(“Missing parameter”)); else context.log(“Here is the visitor”s message: ” + par); response.setContentType(“text/html”); java.io.PrintWriter out = 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. Using JDB Debugger You can debug servlets with the same jdb commands you use to debug an applet or an application. To debug a servlet, we debug sun.servlet.http.HttpServer and carefully watch as HttpServer executes servlets in response to HTTP requests made from browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer. Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for servlets, you have to help your debugger by doing the following − 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 being stopped 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. Client and Server Headers Sometimes when a servlet doesn”t behave as expected, it”s useful to look at the raw HTTP request and response. If you”re familiar with the structure of HTTP, you can read the request and response and see exactly what exactly is going with those headers. Important Debugging Tips Here is a list of some more debugging tips on servlet debugging − Remember 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. Print Page Previous Next Advertisements ”;

Servlets – Page Redirect

Servlets – Page Redirection ”; Previous Next Page redirection is a technique where the client is sent to a new location other than requested. Page redirection is generally used when a document moves to a new location or may be because of load balancing. The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the signature of this method − public void HttpServletResponse.sendRedirect(String location) throws IOException 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 java.io.*; import java.sql.Date; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PageRedirect extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); // New location to be redirected String site = new String(“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 redirect you to URL http://www.photofuntoos.com. Print Page Previous Next Advertisements ”;

Servlets – Database Access

Servlets – Database Access ”; Previous Next This 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 Program FilesMySQLbin C:Program FilesMySQLbin> Step 2 Login to database as follows C:Program FilesMySQLbin>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 int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> Create Data Records Finally you create few records in Employee table as follows − mysql> INSERT INTO Employees VALUES (100, 18, ”Zara”, ”Ali”); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, ”Mahnaz”, ”Fatma”); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, ”Zaid”, ”Khan”); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, ”Sumit”, ”Mittal”); Query OK, 1 row affected (0.00 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.*; public class DatabaseAccess extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // JDBC driver name and database URL static final String JDBC_DRIVER = “com.mysql.jdbc.Driver”; static final String DB_URL=”jdbc:mysql://localhost/TEST”; // Database credentials static final String USER = “root”; static final String PASS = “password”; // Set response content type response.setContentType(“text/html”); PrintWriter out = 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 Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute SQL query Statement 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”); String last = 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 − Database Result 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 Print Page Previous Next Advertisements ”;

Servlets – Handling Date

Servlets – Handling Date ”; Previous Next One 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. Date( ) 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 − Sr.No. Methods & 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. 2 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. 3 Object clone( ) Duplicates the invoking Date object. 4 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. 5 int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. 6 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 long getTime( ) Returns the number of milliseconds that have elapsed since January 1, 1970. 8 int hashCode( ) Returns a hash code for the invoking object. 9 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. 10 String toString( ) Converts the invoking Date object into a string and returns the result. Getting Current Date & Time This is very easy to get current date and time in Java Servlet. You can use a simple Date object with toString() method to print current date and time as follows − // Import required java libraries import java.io.*; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class CurrentDate 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 = “Display Current Date & Time”; Date date = new Date(); 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”>” + date.toString() + “</h2>n” + “</body> </html>” ); } } Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result − Display Current Date & Time Mon Jun 21 21:46:49 GMT+04:00 2010 Try to refresh URL http://localhost:8080/CurrentDate and you would find difference in seconds every time you would refresh. 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. Date Formatting using SimpleDateFormat SimpleDateFormat is a concrete class for formatting and parsing dates in a localesensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. Let us modify above example as follows − // Import required java libraries import java.io.*; import java.text.*; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class CurrentDate 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 = “Display Current Date & Time”; Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat (“E yyyy.MM.dd ”at” hh:mm:ss a zzz”); 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”>” + ft.format(dNow) + “</h2>n” + “</body> </html>” ); } } Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result − Display Current Date & Time Mon 2010.06.21 at 10:06:44 PM GMT+04:00 Simple DateFormat Format Codes To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following − Character Description Example G Era designator AD y Year in four digits 2001 M Month in year July or 07 d Day in month 10 h Hour in A.M./P.M. (1~12) 12 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 234 E Day in week Tuesday D Day in year 360 F Day of week in month 2 (second Wed. in July) w Week in year 40 W Week in month 1 a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. (0~11) 10 z Time zone Eastern Standard Time ” Escape for text Delimiter “ Single quote ` For a complete list of constant available methods to manipulate date, you

Servlets – Hits Counter

Servlets – Hits Counter ”; Previous Next Hit Counter for a Web Page Many 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 java.io.*; import java.sql.Date; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PageHitCounter extends HttpServlet { private int hitCount; public void init() { // Reset hit counter. hitCount = 0; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType(“text/html”); // This method executes whenever the servlet is hit // increment hitCount hitCount++; PrintWriter out = 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>” ); } public void 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 − Total Number of Hits 6 Hit Counter for a Website: Many times you would be interested in knowing total number of hits on your whole website. This is also very simple in Servlet and we can achieve this using filters. Following are the steps to be taken to implement a simple website hit counter which is based on Filter Life Cycle − 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.*; public class SiteHitCounter implements Filter { private int hitCount; public void init(FilterConfig config) throws ServletException { // Reset hit counter. hitCount = 0; } public void 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); } public void destroy() { // This is optional step but if you like you // can write hitCount value in your database. } } Now let us compile the above servlet and create the 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 ……………… Print Page Previous Next Advertisements ”;