Sie sind auf Seite 1von 15

-----------------------------------What are the Differences Between Applets and Servlets The main difference is that a servlet is a server side

component while applet is a client side component, moreover, a servlet dont have GUI while applet have GUI. A servlet runs inside a server and results are sent to client, so it consumes less network bandwidth, and also secure, while applet runs on client side in a browser, so entire code for applet is 1st sent to client and then it is executed on the client machine itself, so it also consumes more network bandwidth. -----------------------------------The basic defference between servlet and applet are as follows: .The applet is client side programming whearas servlet is server side programming. .The program is run over the browser and result sent to the client in case of applet whearas in case of servlet the program will run over the server & result will sent back to client this will take less time to execute a program. .Applet has GUI interface whearas servlet does not have GUI interface -----------------------------------A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlet is an opposite of applet as a serverside applet. Applet is an application running on client while servlet is running on server. -----------------------------------Applet is a part of Core JAVA and Servlet of Advance Java. Applet is client side program and Servlet is Server side. When Applet runs it take the resources of client whereas Servlet is processed at server. An Applet's class, jar files can be accessed and downloadable by client but not so in case of servlet. Applets can run under any web browser their execution is dependent on Client as they require JRE Whereas Servlets do not require any thing specific at client side, as they require java enabled web/application Server. Dilpreet Singh (SCJP,OCA 9i) www.geocities.com/heartsingh Note: There are comments associated with this question. See the discussion page to add to the conversation. -----------------------------------import java.applet.Applet; import java.awt.*; public class AEHousman extends Applet { public void paint ( Graphics gr ) { setBackground( Color.pink ); gr.drawString("Loveliest of trees, the cherry now", 25, 30); gr.drawString("Is hung with bloom along the bough,", 25, 50); gr.drawString("And stands about the woodland ride", 25, 70 ); gr.drawString("Wearing white for Eastertide." ,25, 90); gr.drawString("--- A. E. Housman" ,50, 130); } }

------------------------------------

What is Applet, How to Build an Applet - Java Source Code


Applet: A program designed to be executed from within another application. Unlike an application, applets cannot be executed directly from the operating system. With the growing popularity of OLE (object linking and embedding), applets are becoming more prevalent. A well-designed applet can be invoked from many different applications.

Web browsers, which are often equipped with Java virtual machines, can interpret applets from Web servers. Because applets are small in files size, cross-platform compatible, and highly secure (can't be used to access users' hard drives), they are ideal for small Internet applications accessible from a browser. How applets differ from applications: Applets and standalone application programs are java programs. The difference is the applets are not full featured application programs. They will be used to accomplish a small task. They are usually designed for use on the internet. The limitations and restrictions while using applet are 1. Applet do not use main() 2. Applet cannot run independently. They are run from inside a webpage using a special feature known as HTML tag 3. Applets are restricted from using libraries files from other languages 4. Applet cannot read from or white to the files in the local computer The steps involved in developing and testing an applet are 1. 2. 3. 4. 5. 6. 7. Build an applet code (.java file). Create an executable applet (.class file). Design a web page using HTML tags. Preparing <APPLET> tag. Incorporating <APPLET> into the web page. Creating HTML file. Testing the applet.

Building applet code: The applet code uses the service of 2 classes. 1. Applet 2. Graphics

Applet class is contained in "java.applet" package Graphics class is contained in "java.awt" package The Applet class provides life and behavior to the applet through its methods init(), start(), paint() The paint() of the applet class when called displays result of the applet code on the screen. The paint() takes Graphics object as an argument.

Syntax: Public void paint (Graphics g) Ex: The appletDemo Applet. import java.awt.*; import java.applet.*; public class AppletDemo extends Applet { public void paint(Graphics g) { g.drawString("My First Applet Progrm",20,15); }

In the drawstring(), 20 and 15 denotes position in pixels.

Chain of classes inherited by Applet class:

Designing a Webpage: <HTML> <BODY> <APPLET CODE="AppletDemo.class" WIDTH=300 HEIGHT=400> </APPLET> </BODY> </HTML>

Save the HTML file. In HTML file we have to include <APPLET> and </APPLET> tags in the <BODY> section The <APPLET> contains or supplies the name of the applet to be loaded and tells the browser how much space the applet requires.

Ex: <APPLET CODE=AppletDemo.class WIDTH=300 HEIGHT=400> </APPLET> Note: The <APPLET> specifies

Name of the Applet Width of the Applet (in pixels) Height of the Applet (in pixels)

Adding Applet to HTML file: <HTML> <BODY> <APPLET CODE="AppletDemo.class" WIDTH=300 HEIGHT=400> </APPLET> </BODY> </HTML> Running the Applet: 1. To run the applet we must have the following files in our current directory 1. AppletDemo.java 2. AppletDemo.class 3. AppletTest.html 2. To run an applet we require one of the following tools 1. Java enabled Web browser (Ex: NetScape, Google Chrome, etc) 2. Using 'appletviewer' appletviewer: appletviewer is not a full-fledged web browser and therefore it ignores all the html tags except the part pertaining to the running of the applet. Life Cycle of Applet: When an applet is loaded it undergoes a series of changes in its states. The applet states include 1. 2. 3. 4. Born / Initialization State Running State Idle State Dead / Destroy State

The following is the Applet State transition diagram

Initialization State:

Applet enters the Initialization state when it is first loaded This is achieved by using the init() of Applet class This init() will be applied only once throughout the life cycle of the applet We can override this init() Syntax

public void init() { ----- (actions) --} Running State:


Applet enters into the Running State when the system calls start() of Applet class This method will be called automatically when the applet is initialized The start() can be called any number of times in the life cycle of an applet We may override the start() Syntax

public void start() { ------}

Idle / Stopped State:


The applet becomes idle when it is stopped from running Stopping occurs automatically when we leave the page containing the current running applet We can also explicitly stop the applet by using the stop() of the Applet class We can also override the stop() Syntax

public void stop() { ------} Dead State:


The applet is said to be dead when it is removed from the memory This will automatically down by the system whenever we terminate the applet We can also override the method called destroy() of the Applet class Syntax

public void destroy() { ----- (actions) --} Display State:


Applet moves to the Display state whenever it has to perform some output operations on the screen To perform this the paint() of the Applet class is used Almost every applet contains this paint() If we want to display anything on the screen we must override this method Syntax

public void paint(Graphics g) { ----- (actions) --} Program to demonstrate the life cycle of an Applet

import java.awt.*; import java.applet.*; public class AppLifeDemo extends Applet { public void init() { System.out.println("init method called"); } public void start() { System.out.println("start method called"); } public void stop() { System.out.println("stop method called"); } public void destroy() { System.out.println("destroy method called"); } public void paint(Graphics g) { g.drawString("LIFE CYCLE DEMO",10,20); } } <HTML> <BODY> <APPLET CODE="AppLifeDemo.class" WIDTH=300 HEIGHT=350> </APPLET> </BODY> </HTML> --------------------------------------------------/* <applet code="LifeCycle.class" width=300 height=300></applet> */ import java.applet.Applet; import java.awt.*; public class LifeCycle extends Applet { String output = ""; String event; public void init() { event = "Initializing..."; printOutput(); }

public void start() { event = "Starting..."; printOutput(); } public void stop() { event = "Stopping..."; printOutput(); } public void destroy() { event = "Destroying..."; printOutput(); } private void printOutput() { System.out.println(event); output += event; repaint(); } public void paint(Graphics g) { g.drawString(output, 10, 10); } } ---------------import java.awt.*; import java.applet.*; /*<applet code="SampleApplet" height=500 width=500> </applet> */ public class SampleApplet extends Applet { String msg="Checking Applet Life Cycle"; public void init() { setBackground(Color.blue); msg+="Init Called"; } public void start() { msg+="Start Called"; } public void paint(Graphics g) { msg+="Paint Called"; g.drawString(msg,50,50);

} public void stop() { msg+="Stop Called"; } public void destroy() { msg+="Destroy Called"; } } ---------------import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.applet.Applet; import java.awt.Graphics; public class ExampleEventHandling extends Applet implements MouseListener { StringBuffer strBuffer; public void init() { addMouseListener(this); strBuffer = new StringBuffer(); addItem("initializing the apple "); } public void start() { addItem("starting the applet "); } public void stop() { addItem("stopping the applet "); } public void destroy() { addItem("unloading the applet"); } void addItem(String word) { System.out.println(word); strBuffer.append(word); repaint(); } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);

//display the string inside the rectangle. g.drawString(strBuffer.toString(), 10, 20); } public } public } public } public } void mouseEntered(MouseEvent event) { void mouseExited(MouseEvent event) { void mousePressed(MouseEvent event) { void mouseReleased(MouseEvent event) {

public void mouseClicked(MouseEvent event) { addItem("mouse clicked! "); }

----------------

-------------------------------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 extension mechanisms (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 Java Virtual 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 to access 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, and crash 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 BEA WebLogic 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 sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language. -------------------------------A Generic servlet contains the following five methods: init() public void init(ServletConfig config) throws ServletException

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. 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's request 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 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 getServletInfo() public String getServletInfo() 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 destroy() 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. --------------------------------

Advantages of Java Servlets

1. 2. 3. 4. 5. 6. 7.

Portability Powerful Efficiency Safety Integration Extensibilty Inexpensive

Each of the points are defined below: Portability As 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 can develop 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. Powerful We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy 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 in the server, it remains in the server's memory as a single object instance. However with servlets there 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. Safety As 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 from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception.

Integration Servlets 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. Extensibility The 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. Inexpensive There 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. -------------------------------Java Servlets are the Java solution for providing server-side services over the web by dynamically producing HTML documents, other kinds of documents, or performing other computations in response to communication from the user. They provide a very easy-to-use interface for interacting with client queries and providing server responses. Students who plan to interface with DB2 using JDBC will be working with Java Servlets. Java Servlets interact with the user through HTML forms. For user interaction, you'll have to run a special Servlet program on a specific port on a Unix machine.

Retrieving Input from the User


Input to Servlet programs is passed to the program using web forms. Forms include text fields, radio buttons, check boxes, popup boxes, scroll tables, and the like. Thus retrieving input is a two-step process: you must create an HTML document that provides forms to allow users to pass information to the server, and your Servlet program must have a means for parsing the input data and determining the action to take. This mechanism is provided for you in Java Servlets. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Das könnte Ihnen auch gefallen