Monday 26 November 2012

Java Programming - JSP and Servlets

Java Programming - JSP and Servlets Structure

 1 Introduction Objectives  
2 JSP  2.1 Introduction  
2.2 What is needed to write JSP based web application?  
2.3 How does JSP look?  
2.4 How to test a JSP? Self Assessment Questions  
3 Servlets  
3.1 Introduction  
3.2 History of Web Application  
3.3 Web Architecture  
3.4 Servlet Life Cycle  
4 Summary  
5 Terminal Questions  

1 Introduction JavaServer pages are actually, text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are invoked. Java servlets are a key component of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server‟s functionality. Servlets allow developers to extend and customize any Java-enabled Server- a web server, a mail server, an application server or any custom server.We will see both of these concepts in some detail in the coming subsections. Java

2 JSP  
2.1 Introduction JavaServer pages are on the whole, text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are invoked. The resulting servlet is a combination of the HTML from the JSP file and embedded dynamic content specified by the new tags. That is not to say that JSPs must contain HTML. Some of them will contain only Java code; this is particularly useful when the JSP is responsible for a particular task like maintaining application flow.  

2.2 What is needed to write JSP based web application? As you will come to know in a short time, programming with JSP will need a thorough knowledge of how servlets are written and executed as the code segments inserted in a JSP are mostly Servlet code. If you have already written some ASP programs you may find it easy to work with JSP as there are so many similarities although they are 2 different technologies. To write a JSP code you require an editor. To test the JSPs you need a JSP engine. So this material considers the Java Web Server to the JSP engine. This is the same web server that we considered for testing the Java Servlets.  

2.3 How does JSP look? Before considering more technical details regarding JSP, let us see how a JSP file looks and what its static parts are and what its dynamics parts are:  Consider the HelloWorld.jsp below 1. As you can see a JSP page looks almost like a simple HTML file. In the above HelloWorld.jsp line number 8 is the one accounting for the dynamoc content. All of the rest lines are static HTML content. If you observe line 8 carefully, you can notice that the written code resembles servlet code in some way.  

2.4 How to test a JSP? Once a JSP is written next question is how do you test it? To test JSP we are going to use Java Web Server. The steps are as following:  Copy the HelloWorld.jsp to c:\JavaWebServer2.0\public_html directory· as it is the document root of the Java Web Server . (Assuming that the Java Web Server is installed in c:\)  Now start the Java Web Server‟s web service.·  Open your browser window.·  Now in the address bar type in an address ashttp://IPAddress::· 8080/HelloWorld.jsp, where IP address of your machine.  You should be able to see the output as shown below.· JSP Output Self Assessment Questions  What is JSP?§  What are the uses of JSP?§  

3 Servlets  
3.1 Introduction The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. The Java language was originally intended for use in small, embedded devices. Java‟s potentially as a server-side development platform had been sadly overlooked until recently. Businesses in particular have been quick to recognize Java‟s potential on the server-side. Java is inherently suited for large client/server applications. The cross platform nature of Java is extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the UNIX and Windows operating systems. Java‟s modern, object-oriented, memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java‟s built-in support for networking and enterprise APIs provides access to legacy data, easing the transition from older client/server system. Java servlets are a key component of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server‟s functionality. Servlets allow developers to extend and customize any Java-enabled Server- a web server, a mail server, an application server or any custom server.  

3.2 History of Web Application While servlets can be used to extend the functionality of any Java-enabled server, today they are most often used to extend web servers, providing a powerful, efficient replacement for CGI scripts. When you use servlet to create dynamic content for a web page or otherwise extend the functionality of a web server, you are in effect creating a Web application. While a web page merely displays static content and lets the user navigate through that content, a web application provides a more interactive experience. A web application may be as simple as a key word search on a document archive or as complex as an electronic storefront. Web applications are being deployed on the internet and on corporate intranets and extranets, where they have the potential to increase productivity and change role of servlets in any web application it is necessary to understand the architecture of any current web application.  

3.3 Web Architecture  
2-tier ArchitectureØ Typical client/server systems are all 2-tiered in nature where the application resides entirely on the client PC and database resides on a remote server. But 2-tier systems have some disadvantages such as: The processing load is given to the PC while more powerful server acts· as a traffic controller between the application and the database.  Maintenance is the greatest problem. Imagine a situation where there· is a small modification to be done in the application program. Then in case of a 2-tier architecture system, it is necessary to go to each client machine and make the necessary modifications to the programs loaded on them. That is the reason why the modern web applications are all developed based on 3-tier architecture.  N-tier ArchitectureØ Although the title of this section is given as N-Tier architecture, here the concentration is on the 3-tier architecture. Basic reason for this is that any web application developed based on N-tier architecture functions just similar to typical 3-tier architecture.  

First-Tier:v  Basically the presentation Layer.·  Represented by the GUI kind of thing.·  

Middle-Tier :v  Application Logic·  

Third-Tier :v  Data that is needed for the application.· 

The basic idea behind 3-tier architecture is that to separate application logic from the user interface. This gives the flexibility to the design of the application as well as ease of maintenance. If you compare this with 2-tier architecture, it is very clear that in 3-tier architecture the application logic can be modified without affecting the user interface and the database.  Typical Web ApplicationØ A typical web application consists of following steps to complete a request and response.  Web appli·cation will collect data from the user. (First tier)  Send a request to the web server.·  Run the requested server program. (Second and third tier)·  Package up the data to be presented in the web browser.·  Send it back to the browser for display. (First tier)·

 3.4 Servlet Life Cycle Now that you have seen the basic structure of a servlet, let‟s review the process by which a server invokes a servlet. This process can be broken down into the nine steps as follows:

1. The server loads the servlet when it is first requested by the client or if configured to do so, at server start-up. The servlet may be loaded from either a local or a remote location using the standard Java class loading facility. This step is equivalent to the following code: Class c=Class.forName(“com.sourcestream.MyServlet”); It should be noted that when referring to servlets, the term load often refers to the process of both loading and instantiating the servlet.

2. The server creates one or more instances of the servlet class. Depending on implementation. The server may create a single instance that services all requests through multiple threads or create a pool of instances from which one chosen to service each new request. This step is equivalent to the following Java code: Servlet s=(Servlet) c.newInstance (); where „c‟ is the same Class object created in previous step.  

3. The server constructs a ServerConfig object that provides initialization information to the servlet.

4. The server calls the servlet‟s init () method, passing the object constructed in step 3 as a parameter. The init () method is guaranteed to finish execution prior to the servlet processing the first request. If the server has created multiple servlet instances (step 2), the init () method is called one time for each instance.

5. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client‟s request. It also constructs a ServletResponse or HttpServletResponse object that provides methods for customizing the server‟s response. The type of object passed in these two parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet class, respectively.

6. The server calls the servlet‟s service() method passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads.

7. The service () method processes the client request by evaluating the ServletRequest or HttpServletRequest object and responds using ServletResponse or HttpServletResponse object.

8. If the server receives another request for this servlet, the process begins again at step 5.

9. When instructed to unload the servlet, perhaps by the server administrator or programmatically by the servlet itself, the server calls the servlet‟s destroy() method. The servlet is then eligible for garbage collection. The above mentioned nine steps illustrate the entire lifecycle of a servlet. The following figure shows the flow of the servlet lifecycle. The Java Servlet Development Kit The Java Servlet Development Kit (JSDK) contains the class libraries that you will need to create servlets. A utility known as the servletrunner is also included, which enables you to test some of the servlets that you create. We will use this tool to execute the examples in this chapter. You can download the JSDK without charge from the Sun Microsystems Web site at java.sun.com. Follow the instructions to install this toolkit on your machine. For a Windows machine, the default location of Version 2 of the JSDK is c:\\Jsdk2.0. The directory c:\\Jsdk2.0\\bin contains servletrunner.exe. Update your Path environment variable so that it includes this directory. The directory c:\\Jsdk2.0\\lib contains jsdk.jar. This JAR file contains the classes and interfaces that are needed to build servlets. Update your Classpath environment variable so that it includes c:\\Jsdk2.0\\lib\\jsdk.jar. 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.
2. Start the servletrunner utility.
3. Start a Web browser and request the servlet. 

The following sections examine each of these steps in detail. Create and Compile the Servlet Source Code To begin, create a file named HelloServlet.java that contains the following program: import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Hello!"); pw.close(); } } First, note that this program imports the javax.servlet package, which contains the classes and interfaces required to build servlets. You will learn more about these classes and interfaces later in this chapter. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables a servlet to read data that is provided via the client request. The second argument is an ServletResponse object. This enables a servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html, which indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the HTTP response. Compile this source code and place the HelloServlet.class file in the directory named c:\\Jsdk2.0\\examples. This ensures that it can be located by the servletrunner utility. Start the servletrunner Utility Open a command prompt window and type servletrunner to start that utility. This tool listens on port 8080 for incoming client requests. Start a Web Browser and Request the Servlet Start a Web browser and enter the URL shown here: http://localhost:8080/servlet/HelloServlet  Alternatively, you may enter the URL shown here: http://127.0.0.1:8080/servlet/HelloServlet This can be done because 127.0.0.1 is defined as the IP address of the local machine. You should observe the output of the servlet in the browser display area. It should contain the string Hello! in bold type. Note The examples in this chapter assume that the servletrunner and the Web browser execute on the same machine. However, these two applications can be installed on different machines. In that case, the URLs must be changed to identify the machine on which servletrunner is executing.

 4 Summary  

JavaServer pages are on the whole, text files that combine standard§
 HTML and new scripting tags.  To write a JSP code you require an editor. To test the JSPs you need a§ JSP engine.  Different Web Architecture are:§ o
Simple Web Request-Response Paradigm. o 2-tier Architecture. o N-tier Architecture. o Typically Web Application APPENDIIX JDK Toolls  javac,

The Java CompilerØ The javac program is the tool you use to convert .java files into .class files that can be run by the interpreter. Syntax javac [option] Option Description -classpath Overrides the default CLASSPATH environment variable that contains the standard path for the library classes. -d Specifies the directory for placing the resultant bytecode. -nowarn Turns off the warning messages. -o Turns optimizing on, causing all static, final and private methods to be placed inline. Although this result is faster execution, the .class files become larger. -verbose Generates a message about what the compiler is doing.  

The appletviewer ToolØ Applets, as you have already learned in the earlier section, are programs written in Java that are designed to run embedded in Web pages. You can run these applets using Web browser. The appletviewer tool is a program that lets you run applets without the overhead of running a Web browser. It provides an easy way to test applets written in the Java language.

Syntax appletviewer [option] Option Description -debug Starts the appletviewer in the Java Debugger, jdb, thus allowing you to debug the applets in the HTML document. The applet viewer has an applet menu in the appletviewer window. The options of the Applet menu are listed below. Option Description Restart Restarts the applet using the current settings. Reload Reloads the applets with the changes in the .class file applied. Stop Causes the stop () method of the applet to be called and halts the applet. Save Saves the serialized state of the applet. Start Starts the applet. This is useful when the user selects the stop option from the menu. Clone Duplicates the current applet, to create another AppletViewer instance. Tag Shows the HTML


No comments:

Post a Comment