Powered by Blogger.

Wednesday 25 March 2015

Introducing Servlets

No comments :
Servlets are small programs that execute on the server side of a web connection. Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the functionality extend the functionality of a web server. We will focus on the core concepts, interfaces, and classes. The Life Cycle of a Servlet: 
Three methods are central to the life cycle of a servlet. These are init(), service(), destroy(). They are implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user scenario to understand when these methods are called. First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server. Second, the HTTP request is received by the web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space if the server. Third, the server invokes the init() method of the servlet. This method invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. Fourth, the server invokes service() method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service() method is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy() method to relinquish any resources such as file handles that are allocated for the servlet and its objects can then be garbage collected.
Servlet Development Options: 
To create servlet, you will need access to a servlet container/server. Two popular ones are Glassfish is form Oracle and is provided by the java EE SDK. It is supported by NetBeans. Tomcat is an open-source product maintained by the Apache Software Foundation. It can also be used by NetBeans. Both Tomcat and Glassfish can also be used with other IDEs, such as Eclipse. Although IDEs such as NetBeans and Eclipse are very useful and can streamline the creation of servlets.
Using Tomcat:
Once installed, you start Tomcat by selecting startup.bat form the bin directly under the apache-tomcat directory. To stop Tomcat, execute shutdown.bat, also in the bin directory.
A Simple Servlet:
To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet.  
The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and add the servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Create and Compile the Servlet source Code.



First, note that it imports the javax.servlet package. This package contains the classes and interfaces required to build servlets. The program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that simplifies the creation of a servlet. For Example, it provides versions of init() and destroy(), which may be used as is. You need supply only the service() Method.
The GenericServlet Class:
The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implementation the servlet and ServletConfig interfaces. In addition, a method to append a string to the server log file is available.
The signatures of this method are show here:


Here, s is the String to be appended to the log, and e is an exception that occurred.
The servletInputStream Class:
The servletInputStream class extends InputStream. It is implemented by the servlet container and provides an input stream that a servlet developer cane uses to read the date from the client request. In addition to the input methods. Inherited from InputStream, a method is provided to read bytes from the stream.
It is shown here:

Here, buffer is the array into which size bytes are placed string at offset. The method returns the actual number of bytes of read or -1 if an end-of-stream condition is encountered.
The serverOutputStream Class:
The serverOutputStream class extends OutputStream. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write the data to a client response. In addition to the output method provided by outputStream. It also defines the print() and println() methods, which output data to this stream.
The Servlet Exception Classes:
javax.servlet defines two exceptions. The first is ServletException, which indicates that servlet problem has occurred. The second is UnavailableException, which extends ServletException. It indicates that a servlet is unavailable.
Reading Servlet Parameters:
The servletRequest interface includes method allow you to read the name and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. The example contains two files. A web page is defined in PostParameters.html and a servlet is defined in postParametersServlet.java.

Code of PostParameters.html



Code of postParametersServlet.java



Compile the servlet, Next, copy it to the appropriate directory,and update the web.xml file, as previously described. then, perform these steps to text this example.
 1. Start Tomcat (if is not already running).
 2. Display the web page in a browser.
 3. Enter an Employee name and Phone Number in the text field.
 4. Submit the web page.
After following these steps, the browser will display a response that is dynamically generated by the servlet.

Saturday 14 March 2015

Session Tracking

No comments :
A session is a conversation between the server and a client. A conversation consists series of continuous request and response. HTTP is a stateless protocol. Each request is independent of the previous one. However, in some application, it is necessary to save state information so that information can be collected from several interactions between a browser and a sever. Sessions provide such a mechism. A session can be created via the getSession() method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute(), getAttributeName(), and removeAttribute() methods of HttpSession manage these bindings. Session State is shared by all servlets that are associsted with a client. The following servlet illustrates how to use session state. The getSession() method gets the current session. A new session is created if one does not already exist. The getAttribute() method is called to obtain the object that is bound to the name "date". That object is a Date object that encapsulations the date and time when this page was last accessed. A Date object encapsulating the current date and time is then created. The setAttribute() method is called to bind the name "date" to this object.
Example : 1. Session Tracking code: index.html



2. Session Tracking code: web.xml



3. Session Tracking code: UserVisitServlet.java



when you first request this servlet this servlet, the browser display one line with the current date and time information. On subsequent invocations, two lines are displayed. The first line show the date and time when the servle was last accessed. the second line show the current date and time.

Tuesday 10 March 2015

Servlet Develpment Using Cookies

No comments :
A servlet that illustrates how to use cookies. The servlet is invoked when a form on a web page is submitted. The example contains three files as summarized here:
FileDescription
AddCookie.htmlAllow a user to specify a value for the cookie named MyCookie.
AddCookieServlet.javaProcesses the submission of AddCookie.html
GetCookiesServlet.javaDisplays cookie values.

The HTML, source code for AddCookie.html is shown in the following listing. This page contains a text field in which a value can be entered. There is also a submit button on the page. When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST Request.



The source code for AddCookieServlet.java is shown in the following listing. It gets the value of the parameter named "data". It then creates a Cookie object that has the name "MyCookie" and contains the value of the "data" parameter. The cookie is then added to the header of the HTTP response via the addCookie() method. A feedback message is then written to the browser.



The source code for GetCookiesServlet.java is shown in following listing. It invokes the getCookies() method to read any cookies that are included in the HTTP GET request. The name and values of these cookies are then written to the HTTP response. Observe that the getName() and getValue() method are called to obtain this information.



Compile the servlet, Next, copy it to the appropriate directory,and update the web.xml file, as previously described. then, perform these steps to text this example.
1. Start Tomcat (if is not already running).
2. Display AddCookie.html in Browser.
3. Enter a value for MyCookie.
4. Submit the web page.
After following these steps, you will observe that a feedback message is displayed by the browser.

Tuesday 3 March 2015

HTTP POST Request Handling

No comments :
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a web page is submitted. the example contains two files.
A web page is defined in ColorPost.html, and a servlet is defined in ColorPostServlet.java The HTML source code for ColorPost.html is shown is the following listing. It is identical to ColorGet.html except that the method parameter for the form tag explicitly specifies that the POST method should be used, the action parameter for the form tag specifies a different servlet.



The source code for ColorPostServlet.java is shown in the following listing. the doPost() method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter() method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.



Compile the servlet, Next, copy it to the appropriate directory,and update the web.xml file, as previously described. then, perform these steps to text this example.
1. Start Tomcat (if is not already running).
2. Display the web page in a browser.
3. Enter an Employee name and Phone Number in the text field.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically generated by the servlet.

Sunday 1 March 2015

Handling HTTP Requests And Responses

No comments :
The HttpServlet class provides specialization methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. these methods are doDelete(), doGet(), doHead(), doOptions(),doPost(), and doTrace(). the GET and POST requests are commonly used when handling form input. Handling HTTP GET Requests: Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a web page is submitted. The example contains two files. A web page is defined in ColorGet.html, and a servlet is defined in ColorGetServlet.java. The HTML source code for ColorGet.html is shown in the following listing. It defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTML GET request.

The source code for ColorGetServlet.java is shown in the following listing. the doGet() method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter() method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.

Compile the servlet, Next, copy it to the appropriate directory,and update the web.xml file, as previously described. then, perform these steps to text this example.
1. Start Tomcat (if is not already running).
2. Display the web page in a browser.
3. Enter an Employee name and Phone Number in the text field.
4. Submit the web page.
 After following these steps, the browser will display a response that is dynamically generated by the servlet.