Powered by Blogger.

Display Current Date using GenericServlet

>> Sunday, August 26, 2012

We have a class named Date from java.util.Date package. We can use the Date class methods to display the date. We are going to display this date in the webpage using servlets.

Here we are using init methods to initialize the names and values. with this we can get the names and values from the web.xml file while the program runs. Actually this init(javax.servlet.ServletConfig) method is invoked by the container during initialization phase of the servlet interface.

init() method is a convienience method provided in javax.servlet.GenericServlet class. Generally, it is suggested that init(javax.servlet.ServletConfig) method present in javax.servlet.GenericServlet class should be given a chance to get executed, during servlet's initialization. This method, apart from performing some initialization process, invokes init() method at the end.

Let us come to our Date application using servlet.Using Date calss create a new Date object 'd'. This date object contains the current date. But we can't display the object directly in the webpage. So convert the object to String using toString() method.Then display the date in the form of string in the servlet.

The Structure of our DateApp is :
Date d=new Date();
String s=d.toString();
Use setContentType() method to display in text/html format in the java file of servlet.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

in the above web.xml the mappings are done based on serletname 'ABC'.We can give any name but it should be same in and tags. Based on this the logical name /firstwill be called by Servlet.


package blog.javabynataraj;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class  DateSrv extends GenericServlet
 public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException 
         ServletConfig cg=getServletConfig();
   String s1=cg.getInitParameter("sno");
   String s2=cg.getInitParameter("sname");

  PrintWriter pw=res.getWriter();
  Date d=new Date();
  String s=d.toString();
  pw.println("<b> Date is"+s +"</b>");
  pw.println("<font color=red ><br> Param1 :"+s1+"<br> param2 is:  "+s2+"</font>");


In the above web.xml we used urlpattern as '/first' so while running the program type the url-pattern given in web.xml in the addressbar of your browser.


Download the above Application in jar file.

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.