java4all@1986 java. Powered by Blogger.

How to Display date in Servlet?

>> Wednesday, June 1, 2011

In this example we are going to show how we can display a current date and time on our browser.
It is very easy to display it on our browser by using the Date class of the java.util package.
As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class.
The server invokes doGet() method whenever web server recieves the GET request from the servlet.
The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.
Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object.
HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response.
Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html.
It is the standard MIME content type for the Html pages. The MIME type tells the browser what kind of data the browser is about to receive.
After that it has used the method getWriter() of the response object to retrieve a PrintWriter object.
To display the output on the browser we use the println() method of the PrintWriter class.
The coding is shown below :
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayingDate extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
Date today = new Date();
pw.println("<html>"+"<body><h1>Today Date is</h1>");
pw.println("<b>"+ today+"</b></body>"+ "</html>");
}
}
WEB.XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>DateDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/DateDisplay</url-pattern>
</servlet-mapping>
</web-app>

The output will be the present date

Read more...

A simple and easily understandable example in servlet?

We should start understanding the servlets from the beginning.
Lets start by making one program which will just print the "Hello World" on the browser.
Each time the user visits this page it will display "Hello World" to the user on ClientMachine.

As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class.
The server invokes doGet() method  whenever web server recieves the GET request from the servlet.
The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.
Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object.
HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response.
Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html. It is the standard MIME content type for the Html pages. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object.  To display the output on the browser we use the println() method of the PrintWriter class.


Below is the a small simple program.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></title>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}

WEB.XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>


The outout of the above program is:
                                              

Read more...

Difference Between Generic Servlet And HttpServlet?

Difference Between GenericServlet and HttpServlet:

1.)Generic Servlets are protocol independent, where as HttpServlet  are protocol dependent.

2.)Generic Servlets are incompatible with HTTP methods,where as HttpServlets are compatible with HTTP Methods.
3.)GenericServlet will not give an option for developers to specify different types of request at client machine,where HTTPServlets are Developers friendly.
4.)For each and every request type(Get,Post,Put,..) GenericServlet will use same execution mechanism ,where as HTTPServlets will separate execution process for each and request type.

Read more...

Life Cycle of Servlet?

Life Cycle of Servlet:




When we sent a request from client to server, the protocol will establish a socket connection Between Client and Server.Then the protocol will carry the client request to server machine.At server machine there are Main Server and Container.First the Main Server will Validates the client request ,if it is successfully then it will bypass to Container,Then the Container will perform the following steps.
1.)The container will get the requested Uri with Application name and resource name .It checks for the resources name i.e whether it is html/jsp ,if it is html/jsp then the Container will get requested Resource above WEB-INF which is in public area.
2.)If the requested resource is not html/jsp ,then it will think that is an url-pattern which is available under WEB-INF.
3.)Then the container will go to Web.XML and find the respective resources i.e Servlet by matching the URL-pattern,then the  Container will reform the following steps      

  1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
  2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

    The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
  3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
  4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.

                

Read more...

What is meant b Servlet and it's Methods?

Servlet:It is an object ,which can be used to generate dynamic response from server.
Methods In Servlet:
1.)public void init(ServletConfig config) throws Servlet Exception

The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. 
The servlet cannot be put into the service if
  •  The init() method does not return within a fix time set by the web server. 
  •  It throws a ServletException
Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.

2.)public void service(ServletRequest request,ServletResponse response) throws IO Exception,servlet Exception
Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and  javax.servlet.ServletResponse are passed by the servlet container. 

The status code of the response always should be set for a servlet that throws or sends an error.

Parameters -  The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.

3.)public String getServletInfo();

This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.
Returns -  the ServletConfig object


4.)public ServletConfig getServletConfig();

The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. 
 Returns - a string that contains the information about the servlet

5.)public void destroy();
This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.

Read more...

What is meant by Http status code?

It is a number representation which can be used to known the request processing and response generation.
Status code are of five types

1.)1xx  means Information code(100-199)
2.)2xx means Successful status code(200-299)
3.)3xx means Re directional status code(300-399)
4.)4xx means client side error(400-499)
5.)5xx means server side error(500-599)

Read more...

Explaination of each methods in Http Protocol?

Difference Between Get() and Head():
   Get() can be used to download the data from the requested resource,where as Head() can be used to get the data from the requested resources as well as meta data of the requested resource.That means Head() is using get() internally.

Difference Between Post() and put():
Both these can be used to upload data in server,if we use post() to upload data on server it is not required to specify location.If we use put() to upload data on server it is required to specify location on server.
Difference Between Get() and Post()

1.)Get() method is default method ,where as post() is not default method.

2.)Get() method had only header part,it doesn't had body part, where as post() had both header part and as well as  body part.

3.)Due to lack of body part in get() method it is unable to store the client specified i/p data in header part, because header part having limitations upto 256 characters .In post() due to availability of body part ,it will store large n.o i./p provided by the client,because body part doesn't have limitation of memory.

Option(): This method can be used to known that how many methods are supported by our sever machine.Some servers may support some methods and some other may not.


Trace():This method can be used to check the status of our server,whether it works like echo server.

Delete(): This method can be used to delete data from server,but it is not supported by all server machines.

Read more...

Difference between GET() and POST()?

Difference Between Get() and Post()

1.)Get() method is default method ,where as post() is not default method.

2.)Get() method had only header part,it doesn't had body part, where as post() had both header part and as well as  body part.

3.)Due to lack of body part in get() method it is unable to store the client specified i/p data in header part, because header part having limitations upto 256 characters .In post() due to availability of body part ,it will store large n.o i./p provided by the client,because body part doesn't have limitation of memory.

4.)Due to lack of body part get() method doesn't provide security,where post()  method will provide security.

5.)Mainly get() can be used to download data for server, post() can be used to upload data on server. 

Read more...

What are the Http Protocol methods?

Http protocol gives an option to developers to specify some method at client machine
   HTTP METHODS
1.)GET
2.)POST
3.)HEAD
4.)POST
5.)TRACE
6.)OPTION
7.)DELETE

Read more...

How will Http protocol will maintain it's statless behaviour?

                                                     
Client server Architecture
               1.)When we sent a request from client to server ,the protocol will establish a socket connection between client and server.Upon receiving the request the protocol will prepare a request format consists of header part and body part.
                 2.)In header part it will maintain client and server ip address and in body part it will maintain client specified input data.
                  3.)The protocol will carry the request format to the server ,then the server generate the dynamic response and keep in the request object and send to the protocol.
                   4.)Then the protocol will prepare a response format and carry the response generation to client machine.
                   5.)When the response reached to client machine ,the protocol will terminate the establish socket connection between client and server.
                  6.)  This means that protocol will not remember  the previous conservation data at the time of processing the later request.

                                            It means that HTTP protocol will maintain the stateless nature. 
                                    

Read more...

What type of protocol we are using in our application?

Protocol:It is set of rules and regulations which can be used to carry data from one machine to another machine.
           We need the protocol that should follow the below rules:
          1.)It should not have physical connection.
          2.)It should be statementless.
          3.)It should be compatible to carry the hyper text data from client to server and server to client machine.
     So we are using HTTP protocol in our application because it follows all the above rules.

Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP