make or modify the manifest

28
Make or modify the Manifest.MF to YourManifest.MF. 1) YourClassNameWithMain is the class name (case sensitive) without .class extension 2) No extra spaces following the YourClassName withMain. Manifest-Version:1.0 Main-Class: YourClassNameWithMain Created-by:1.2(Sun Microsystems Inc.) On Command line : type the following  jar cvfm YourJarFileName.jar YourManifest.MF* or  jar cvfm YourJarFileName.jar YourManifest.MF -C classes yourClassPath Drag-drop the YourJarFileName.jar to your desktop double click it, it runs If your program only has System.out.println ("whatever"); statements , it will display nothing. The same will happen when you run it useing java at co mmand line You need some windows code to see it run Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similar to zip utility, and more Java. You can use it on any machine installed JDK Create a folder name it anything Make that folder your cu rrent directory put all your files for turning in (do not put any extra) in that directory. Be sure to put your html file, if there is one At your dos prompt, while you are in the directory that you created , type in:  jar cvf Prj02.jar* This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02 that can be replaced by any of your desired jar file name. To test it, you can extract the contents of jar file by typing:  jar xvf Prj02.jar 1. import ja va.awt.*;

Upload: suganya-nagarajan

Post on 06-Apr-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 1/28

Make or modify the Manifest.MF to YourManifest.MF.

1) YourClassNameWithMain is the class name (case sensitive) without .class extension2) No extra spaces following the YourClassName withMain.

Manifest-Version:1.0Main-Class: YourClassNameWithMain

Created-by:1.2(Sun Microsystems Inc.)On Command line : type the following

 jar cvfm YourJarFileName.jar YourManifest.MF*

or 

 jar cvfm YourJarFileName.jar YourManifest.MF -C classes yourClassPathDrag-drop the YourJarFileName.jar to your desktop double click it, it runsIf your program only has System.out.println ("whatever"); statements, it willdisplay nothing. The same will happen when you run it useing java at command line

You need some windows code to see it run

Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similar to ziputility, and more Java.

You can use it on any machine installed JDK

Create a folder name it anythingMake that folder your current directoryput all your files for turning in (do not put any extra) in that directory.

Be sure to put your html file, if there is oneAt your dos prompt, while you are in the directory that you created , type in:

 jar cvf Prj02.jar*

This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02 thatcan be replaced by any of your desired jar file name.

To test it, you can extract the contents of jar file by typing: jar xvf Prj02.jar 

1. import java.awt.*;

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 2/28

2. import java.awt.event.*;

3. import java.applet.*;

4. import javax.swing.*;

5. import java.lang.*;

6.

7.

8. public class Kol2_1 extends  Applet implements  ActionListener

9. {

10.  Button plus = new Button("+");

11.  Button minus = new Button("-");

12.  Button times = new Button("*");

13.  Button div = new Button("/");

14.  Button eq = new Button("=");

15.

16.  TextField pole = new TextField ("E hej zver");

17.

18.  double x=0.0,y=0.0, z;

19.

20.

21.   public  void init()

22.  { 

23.  try{

24. x=Double.parseDouble(JOptionPane.showInputDialog("Vnesete vrednost

za x:"));

25. y=Double.parseDouble(JOptionPane.showInputDialog("Vnesete vrednost

za y:"));

26.  }

27.  catch(StringIndexOutOfBoundsException n)

28.  {JOptionPane.showMessageDialog(this, "Vnesete broj.");} 29.

30. setLayout(new GridLayout(4,2));

31. add(plus);

32. add(minus);

33. add(times);

34. add(div);

35. add(eq);

36. add(pole);

37.

38. plus.addActionPerformed(this); /*cannot find symbol method 

addActionPerformed(Kol2_1)*/ 39. minus.addActionPerformed(this); /*cannot find symbol method 

addActionPerformed(Kol2_1)*/ 

40. times.addActionPerformed(this); /*cannot find symbol method 

addActionPerformed(Kol2_1)*/ 

41. div.addActionPerformed(this); /*cannot find symbol method 

addActionPerformed(Kol2_1)*/ 

42. eq.addActionPerformed(this); /*cannot find symbol method 

addActionPerformed(Kol2_1)*/ 

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 3/28

43.

44.

45.

46.

47.  }

48.

49.   public  void actionPerformed( ActionEvent e)

50.  {

51.  switch(e.getSource()){  //incompatible types

52.  case plus: { z=x+y;}

53.  case minus: { z=x-y;}

54.  case times: { z=x*y;}

55.  case div: {  try{z=x/y;}

56.  catch( NumberFormatException m)

57.  {

58.  if(y==0)

JOptionPane.showMessageDialog(this,"Division by zero.");

59.  }

60.  }

61.  case eq: {pole.setText(""+z);}

62.  }

63.  }

64. }

import java.aw t.*;

import java.aw t.event.*;

import java.applet.*;

import javax.sw ing.*;

import java.lang.*;

import javax.swing.*;

08 import java.awt.*;

09 import java.awt.event.*;

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 4/28

10 import java.text.*;

11  

12 public class tempCon extends JApplet implements ActionListener {

13  

14 JTextField txtInput;

15 JLabel lblResult;

16 JRadioButton rbCelcius, rbKelvin;

17  

18 public void init(){

19  

20 Container conpane = getContentPane();

21 conpane.setLayout (new FlowLayout());

22  

23 txtInput = new JTextField("",10);

24 conpane.add(txtInput);

25  

26 rbCelcius= new JRadioButton ("to Celcius", true);

27 conpane.add(rbCelcius);

28  

29 rbKelvin = new JRadioButton("to Kelvin", false);

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 5/28

30 conpane.add(rbKelvin);

31  

32 ButtonGroup selection = new ButtonGroup();

33 selection.add(rbCelcius);

34 selection.add(rbKelvin);

35  

36 JButton button1 = new JButton ("Show Result");

37 button1.addActionListener(this);

38 conpane.add(button1);

39  

40 lblResult= new JLabel ("Enter Ferenheit, Choose an option toconvert and Click Show Result");

41 conpane.add(lblResult);

42 }

43  

44 public void actionPerformed(ActionEvent e) {

45  

46 DecimalFormat df = new DecimalFormat ("#.##");

47 double ferenheit = Double.parseDouble(txtInput.getText());

48 double answer = 0.0;

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 6/28

49  

50 answer = ((5.0/9.0)*(ferenheit - 32.0));

51 

52 if (rbKelvin.isSelected())

53 answer += 273.15;

54  

55 lblResult.setText(String.valueOf(df.format(answer)));

56  

57 }

58 }

• And the HTML file goes as below. Save this file as any_name.htm, and place it in thesame folder that has the compiled class file (tempCon.class) of the above java file(tempCon.java)

• view source 

• print?

1 <html>

2 <body>

3 <APPLET CODE="tempCon" width=400 height=400></APPLET>

4 </body>

5 </html>

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 7/28

Servlet

Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building

Web-based applications

, without the performance limitations of CGI programs. Unlike proprietary server extensionmechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers,

 platforms, and tools. Using servlets web developers can create fast and efficient server side

application which can run on any servlet enabled web server . Servlets run entirely inside the JavaVirtual Machine. Since the Servlet runs at server side so it does not checks the browser for 

compatibility. Servlets can access the entire family of Java APIs, including the JDBC API toaccess enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all

the benefits of the mature java language including portability, performance, reusability, andcrash protection. Today servlets are the popular choice for building interactive web applications.Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others.

Servlet containers are usually the components of web and application servers, such as BEAWebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System

Application Server and others.

Servlets are not designed for a specific protocols. It is different thing that they are most

commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticatedserver side extensions in a server as they follow the standard framework and use the highly

 portable java language.

HTTP Servlet typically used to:

• Priovide dynamic content like getting the results of a database query and returning to theclient.

• Process and/or store the data submitted by the HTML.

• Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.

Methods of servlet

Generic servlet contains the following five methods:

init()

public void init(ServletConfig config) throws ServletException

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 8/28

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 ServletExceptionParameters - 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.

service()

public void service(ServletRequest req, ServletResponse res) throws ServletException,IOException

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'srequest and the object ServletResponse contains the servlet's response. The service() method

throws ServletException and IOExceptions exception. 

getServletConfig()

public ServletConfig getServletConfig() 

This method contains parameters for initialization and startup of the servlet and returns aServletConfig object. This object is then passed to the init method. When this interface isimplemented 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

getServletInfo()

public String getServletInfo() 

The information about the servlet is returned by this method like version, author etc. Thismethod 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

destroy()

public void destroy() 

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 9/28

This method is called when we need to close the servlet. That is before removing a servletinstance 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 theexit 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.

Life cycle of servlet

The life cycle of a servlet can be categorized into four parts:1. Loading and Inatantiation: The servlet container 

loads the servlet during startup or when the first request is made. The loading of theservlet 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 becalled by the servlet container before the servlet can service any request. Theinitialization 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 servletcontainer unloads the servlet.

3. Servicing the Request: After successfully completing the initialization process, theservlet 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, theservlet container calls the destroy() method . Like the init() method this method is alsocalled only once throughout the life cycle of the servlet. Calling the destroy() methodindicates 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 memoryassociated with the resources for garbage collection.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 10/28

Life Cycle of a Servlet 

Advantages of servlet

1. Portability 

2. Powerful 

3. Efficiency 

4. Safety 

5. Integration 

6. Extensibilty 

7. Inexpensive 

Each of the points are defined below:

PortabilityAs we know that the servlets are written in java and follow well known standardized APIs so

they are highly portable across operating systems and server implementations. We candevelop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running

on the iPlanet/Netscape Application server. So servlets are write once, run anywhere(WORA) program.

PowerfulWe can do several things with the servlets which were difficult or even impossible to do withCGI, for example the servlets can talk directly to the web server while the CGI programs can't

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 11/28

do. Servlets can share data among each other, they even make the database connection poolseasy to implement. They can maintain the session by using the session tracking mechanism

which helps them to maintain information from request to request. It can do many other things which are difficult to implement in the CGI programs.

Efficiency

As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded inthe server, it remains in the server's memory as a single object instance. However with servletsthere are N threads but only a single copy of the servlet class. Multiple concurrent requests are

handled by separate threads so we can say that the servlets are highly scalable.

SafetyAs servlets are written in java, servlets inherit the strong type safety of java language. Java's

automatic garbage collection and a lack of pointers means that servlets are generally safe frommemory management problems. In servlets we can easily handle the errors due to Java'sexception handling mechanism. If any exception occurs then it will throw an exception.

IntegrationServlets are tightly integrated with the server. Servlet can use the server to translate the file

 paths, perform logging, check authorization, and MIME type mapping etc.

ExtensibilityThe servlet API is designed in such a way that it can be easily extensible. As it stands today,the servlet API support Http Servlets, but in later date it can be extended for another type of 

servlets.

InexpensiveThere are number of free web servers available for personal use or for commercial purpose.Web servers are relatively expensive. So by using the free available web servers you can add

servlet support to it.

Advantages of sevlets over CGI

Servlets are server side components that provides a powerful mechanism for developing server web applications for server side. Earlier CGI was developed to provide server side capabilitiesto the web applications. Although CGI played a major role in the explosion of the Internet, its

 performance, scalability and reusability issues make it less than optimal solutions. JavaServlets changes all that. Built from ground up using Sun's write once run anywhere

technology java servlets provide excellent framework for server side processing.

Using servlets web developers can create fast and efficient server side applications and can runit on any servlet enabled web server. Servlet runs entirely inside the Java Virtual Machine.Since the servlet runs on server side so it does not depend on browser compatibility.

Servlets have a number of advantages over CGI and other API's. They are:

1. Platform IndependenceServlets are written entirely in java so these are platform independent. Servlets can run on

any Servlet enabled web server. For example if you develop an web application inwindows machine running Java web server , you can easily run the same on apache web

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 12/28

server (if Apache Serve is installed) without modification or compilation of code.Platform independency of servlets provide a great advantages over alternatives of 

servlets.

2. PerformanceDue to interpreted nature of java, programs written in java are slow. But the java servlets

runs very fast. These are due to the way servlets run on web server. For any programinitialization takes significant amount of time. But in case of servlets initialization takes place first time it receives a request and remains in memory till times out or server shutdowns. After servlet is loaded, to handle a new request it simply creates a new thread andruns service method of servlet. In comparison to traditional CGI scripts which creates a

new process to serve the request.

3. ExtensibilityJava Servlets are developed in java which is robust, well-designed and object orientedlanguage which can be extended or polymorphed into new objects. So the java servletstake all these advantages and can be extended from existing class to provide the ideal

solutions.

4. SafetyJava provides very good safety features like memory management, exception handling

etc. Servlets inherits all these features and emerged as a very powerful web server extension.

5. SecureServlets are server side components, so it inherits the security  provided by the web

server. Servlets are also benefited with Java Security Manager.

Features of servlets

This version has been released on September 26, 2005 by the Sun MicroSystems. It is notnecessary that all web servers and application servers support the features of Servlet 2.5. Still

most of the popular containers like Tomcat 5.5 and JBoss 4.0 support Servlet 2.4.

The list of the added features is given below:

1. Dependency on J2SE 5.0: The minimum platform requirement for Servlet 2.5 is JDK 1.5. Servet 2.5 can't be used in versions below than JDK1.5. All the available features of JDK1.5 like generics, autoboxing, an improved for loop etc are guaranteed available to

Servlet 2.5  programmers.

2. Support For annotations: Annotations provide a mechanism for decorating java codeconstructs (classes, methods, fields, etc.) with metadata information. Annotations are

mark code in such a way that code processors may alter their behavior based on themetadata information.

3. Several web.xml convenience: Servlet 2.5 introduces several small changes to theweb.xml file to make it more convenient to use. For example while writing a <filter-mapping>, we can now use an asterisk in a <servlet-name> which will represent all

servlets as well as JSP.

Previously we used to do

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 13/28

<filter-mapping><filter-name>FilterName</filter-name>

<servlet-name>FilterName</servlet-name></filter-mapping>

 Now,

<filter-mapping><filter-name>FilterName</filter-name>

<servlet-name>*</servlet-name></filter-mapping>

Previously in <servlet-mapping> or <filter-mapping> there used to be only one <url- pattern>, but now we can have multiple <url-pattern>, like

<servlet-mapping>

<servlet-name>abc</servlet-name><url-pattern>/abc/*</url-pattern><url-pattern>/abc/*</url-pattern>

</servlet-mapping>

Apart from these changes, many more facilities added in web.xml.

4. A Handful of removed restrictions: Servlet 2.5 removed a few restrictions around error handling and session tracking. Now it has removed the restriction that the <error-page>

could not call the setStatus() method to alter the error code that triggered them. In sessiontracking, Servlet 2.5 eased a rule that a servlet called by RequestDispatcher include()

couldn't set response headers.

5. Some edge case clarifications: The servlet 2.4 specification says that before callingrequest.getReader() we must call request.setCharacterEncoding(). However there is no

such clarification given why it is so.

Overview of servlets

This tutorial covers concepts pertaining to Server side programming in general and Java Servlets

in particular. In addition, it demonstrates as how to create and compile a simple

Servlet and finally execute it using a Web Server such as an Apache Tomcat Server.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 14/28

It also guides the student through a step by step approach as how to install the

above Server, configure it and create the relevant folders and files. After completion

of this tutorial, the student would not only be familiar with Servlet fundamentals,

but also get hands-on experience in terms of creating and executing simple Servlet

programs.

1. Introduction to Server Side Programming

2. Introduction to Java Servlets

3. Installation, Configuration and running Servlets

Introduction to Server Side Programming

All of us (or most of us) would have started programming in Java with the ever famous “HelloWorld!” program. If you can recollect, we saved this file with a .java extension and later 

compiled the program using javac and then executed the class file with java. Apart fromintroducing you to the language basics, the point to be noted about this program is that – “It isa client side program”. This means that you write, compile and also execute the program on aclient machine (e.g. Your PC). No doubt, this is the easiest and fastest way to write, compile

and execute programs. But, it has little practical significance when it comes to real world programming.

1. Why Server Side Programming?

Though it is technically feasible to implement almost any business logic using client side programs, logically or functionally it carries no ground when it comes to enterprise

applications (e.g. banking, air ticketing, e-shopping etc.). To further explain, going by the

client side programming logic; a bank having 10,000 customers would mean that eachcustomer should have a copy of the program(s) in his or her PC which translates to

10,000 programs! In addition, there are issues like security, resource pooling, concurrentaccess and manipulations to the database which simply cannot be handled by client side

 programs. The answer to most of the issues cited above is – “Server Side Programming”.Figure-1 illustrates Server side architecture in the simplest terms.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 15/28

2. Advantages of Server Side Programs

The list below highlights some of the important advantages of Server Side programs.

i. All programs reside in one machine called the Server. Any number of remotemachines (called clients) can access the server programs.

ii. New functionalities to existing programs can be added at the server side which theclients’ can advantage without having to change anything from their side.

iii. Migrating to newer versions, architectures, design patterns, adding patches,switching to new databases can be done at the server side without having to

 bother about clients’ hardware or software capabilities.

iv. Issues relating to enterprise applications like resource management, concurrency,session management, security and performance are managed by service side

applications.

v. They are portable and possess the capability to generate dynamic and user-basedcontent (e.g. displaying transaction information of credit card or debit card

depending on user’s choice).

3. Types of Server Side Programs

i. Active Server Pages (ASP)

ii. Java Servlets

iii. Java Server Pages (JSPs)

iv. Enterprise Java Beans (EJBs)

v. PHP 

To summarize, the objective of server side programs is to centrally manage allprograms relating to a particular application (e.g. Banking, Insurance, e-shopping,

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 16/28

etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XPProfessional, MS Internet Explorer and an internet connection) can experience the

power and performance of a Server (e.g. IBM Mainframe, Unix Server, etc) from aremote location without having to compromise on security or speed. More

importantly, server programs are not only portable but also possess the capability

to generate dynamic responses based on user’s request.

Introduction to Java Servlets

Java Servlets are server side Java programs that require either a Web Server or an ApplicationServer for execution. Examples for Web Servers include Apache’s Tomcat Server and

Macromedia’s JRun. Web Servers include IBM’s Weblogic and BEA’s Websphere server.Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java

Beans (EJBs). In the forthcoming sections, we will get acquainted with Servlet fundamentalsand other associated information required for creating and executing Java Servlets.

1. Basic Servlet Structure 

As seen earlier, Java servlets are server side programs or to be more specific; webapplications that run on servers that comply HTTP protocol. The javax.servlet and

 javax.servlet.http packages provide the necessary interfaces and classes to work withservlets. Servlets generally extend the HttpServlet class and override the doGet or the

doPost methods. In addition, other methods such as init, service and destroy also called aslife cycle methods might be used which will be discussed in the following section. The

skeleton of a servlet is given in Figure

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 17/28

 

2. A Servlet’s Life CycleThe first time a servlet is invoked, it is the init method which is called. And remember 

that this is called only once during the lifetime of a servlet. So, you can put all your initialization code here. This method next calls the service method. The service method inturn calls the doGet or doPost methods (whichever the user has overridden). Finally, the

servlet calls the destroy method. It is in a sense equivalent to the finally method. You canreset or close references / connections done earlier in the servlet’s methods (e.g. init,

service or doGet /doPost). After this method is called, the servlet ceases to exist for all practical purposes. However, please note that it is not mandatory to override all these

methods. More often than not, it is the doGet or doPost method used with one or more of the other life cycle methods.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 18/28

3. A Servlet Program

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 19/28

 

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 20/28

Output Screens

To appreciate the execution of the servlet life cycle methods, keep refreshing the browser (F5 in Windows). In the background, what actually happens is – with each refresh, thedoGet method is called which increments i’s value and displays the current value. Find

 below the screen shots (Figures 5 through 7) captured at random intervals. The procedureto run the servlets using a Web Server will be demonstrated in the next section (1.3.).

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 21/28

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 22/28

Installation, Configuration and running Servlets

In this section, we will see as how to install a WebServer, configure it and finally run servlets

using this server. Throughout this tutorial, we will be using Apache’s Tomcat server as theWebServer. Tomcat is not only an open and free server, but also the most preferred WebServer 

across the world. A few reasons we can attribute for its popularity is – Easy to install andconfigure, very less memory footprint, fast, powerful and portable. It is the ideal server for 

learning purpose.

1. Installation of Tomcat Server and JDK 

As mentioned earlier, Apache’s Tomcat Server is free software available fordownload @ www.apache.org. The current version of Tomcat Server is 6.0 (as

of November 2007). This Server supports Java Servlets 2.5 and Java ServerPages ( JSPs) 2.1 specifications. In case of doubt or confusion, you can refer to

the abundant documentation repository available on this site.

Important software required for running this server is Sun’s JDK (JavaDevelopment Kit) and JRE (Java Runtime Environment). The current version of 

 JDK is 6.0. Like Tomcat, JDK is also free and is available for download atwww.java.sun.com.

2. Configuring Tomcat Server

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 23/28

○ Set JAVA_HOME variable - You have to set this variable which points tothe base installation directory of JDK installation. (e.g. c:\program

file\java\jdk1.6.0). You can either set this from the command prompt orfrom My Computer

-> Properties -> Advanced -> Environment Variables.

○ Specify the Server Port – You can change the server port from 8080 to80 (if you wish to) by editing the server.xml file in the conf folder. Thepath would be something like this – c:\program files\apache software

foundation\tomcat6\conf\server.xml

3. Run Tomcat Server

Once the above pre-requisites are taken care, you can test as whether theserver is successfully installed as follows:

Step 1

• Go to C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin anddouble click on tomcat6

OR

• Go to Start->Programs->Apache Tomcat 6.0 -> Monitor Tomcat. You willnotice an icon appear on the right side of your Status Bar. Right click on this

icon and click on Start service.

Step 2

• Open your Browser (e.g. MS Internet Explorer) and type the following URL :

http://localhost/ (If you have changed to port # to 80)

OR

• Open your Browser (e.g. MS Internet Explorer) and type the following URL :

http://localhost:8080/ (If you have NOT changed the default port #)

In either case, you should get a page similar to the one in Figure-8 whichsignifies that the Tomcat Server is successfully running on your machine.

4. Compile and Execute your Servlet

 This section through a step by step (and illustration) approach explains ashow to compile and then run a servlet using Tomcat Server. Though thisexplanation is specific to Tomcat, the procedure explained holds true for

other Web servers too (e.g. JRun, Caucho’s Resin).

Step 1 – Compile your servlet program

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 24/28

 The first step is to compile your servlet program. The procedure is nodifferent from that of writing and compiling a java program. But, the point tobe noted is that neither the javax.servlet.* nor the javax.servlet.http.* is partof the standard JDK. It has to be exclusively added in the CLASSPATH. The setof classes required for writing servlets is available in a jar file called servlet-api.jar. This jar file can be downloaded from several sources. However, the

easiest one is to use this jar file available with the Tomcat server (C:\ProgramFiles\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar). You need toinclude this path in CLASSPATH. Once you have done this, you will be able to

successfully compile your servlet program. Ensure that the class file iscreated successfully.

Step 2 – Create your Web application folder

 The next step is to create your web application folder. The name of the foldercan be any valid and logical name that represents your application (e.g.

bank_apps, airline_tickets_booking, shopping_cart,etc). But the mostimportant criterion is that this folder should be created under webapps folder.

 The path would be similar or close to this - C:\Program Files\Apache SoftwareFoundation\Tomcat 6.0\webapps. For demo purpose, let us create a folder

called demo-examples under the webapps folder.

Figure- depicts the same.

Step 3 – Create the WEB-INF folder

 The third step is to create the WEB-INF folder. This folder should be createdunder your web application folder that you created in the previous step.

Figure-10 shows the WEB-INF folder being placed under the demo-examplesfolder.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 25/28

Figure – WEB-INF folder inside web application folder

Step 4 – Create the web.xml file and the classes folder

 The fourth step is to create the web.xml file and the classes folder. Ensurethat the web.xml and classes folder are created under the WEB-INF folder.Figure-11 shows this file and folder being placed under the WEB-INF folder.

Figure – web.xml file and the classes folder

Note – Instead of creating the web.xml file an easy way would be to copy anexisting web.xml file (e.g. C:\Program Files\Apache Software

Foundation\Tomcat 6.0\webapps\examples\WEB-INF) and paste it into thisfolder. You can later edit this file and add relevant information to your web

application.

Step 5 – Copy the servlet class to the classes folder

We need to copy the servlet class file to the classes folder in order to run theservlet that we created. All you need to do is copy the servlet class file (the

file we obtained from Step 1) to this folder. Figure-12 shows the

servlet_lifecycle (refer section 1.2.3.) class being placed in the classes folder.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 26/28

Figure – servlet class file placed under classes folder

Step 6 – Edit web.xml to include servlet’s name and url pattern

 This step involves two actions viz. including the servlet’s name and thenmentioning the url pattern. Let us first see as how to include the servlet’sname in the web.xml file. Open the web.xml file and include the servlet’s

name as shown in Figure-13.

Figure– Include servlet’s name using the <servlet> </servlet> tag

Note – The servlet-name need not be the same as that of the class name.

 You can give a different name (or alias) to the actual servlet. This is one of the main reasons as why this tag is used for.

Next, include the url pattern using the <servlet-mapping> </servlet-mapping> tag. The url pattern defines as how a user can access the servlet

from the browser. Figure-14 shows the url pattern entry for our currentservlet.

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 27/28

Figure – Include url-pattern using the <servlet-mapping> </servlet-mapping> tag

Note – Please remember that the path given in the url-pattern is a relativepath. This means that this path is w.r.t. your web applications folder (demo-

examples in this case).

Step 7 – Run Tomcat server and then execute your Servlet

 This step again involves two actions viz. running the Web Server and thenexecuting the servlet. To run the server, follow the steps explained in Section

1.3.3.

After ensuring that the web server is running successfully, you can run yourservlet. To do this, open your web browser and enter the url as specified in

the web.xml file. The complete url that needs to be entered in the browser is:

http://localhost/demo-examples/servlet_lifecycle

8/3/2019 Make or Modify the Manifest

http://slidepdf.com/reader/full/make-or-modify-the-manifest 28/28

Figure – Our servlet’s output!

Eureka! Here’s the output of our first servlet. After a long and pain staking

effort, we finally got an output! As mentioned in Section 1.2.3. you can keeprefreshing the browser window and see for yourself as how i value is

incremented (a proof that the doGet is called every time you re-invoke aservlet).