chapter 3

123
Chapter 3 JAVA APPLET & SERVLET

Upload: megha

Post on 02-Dec-2015

25 views

Category:

Documents


3 download

DESCRIPTION

JAVA applet

TRANSCRIPT

Chapter 3

Chapter 3JAVA APPLET & SERVLET AppletApplet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. Advantage of AppletIt works at client side so less response time.SecuredIt can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc.

Drawback of AppletPlug-in is required at client browser to execute applet.

Hierarchy of Applet

There are some important differences between an applet and a standalone Java application, including the following:

An applet is a Java class that extends the java.applet.Applet class.A main() method is not invoked on an applet, and an applet class will not define main().Applets are designed to be embedded within an HTML page.When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine. A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet:The java.applet.Applet class provides 4 life cycle methodsand java.awt.Component class provides 1 life cycle methodsfor an applet.

A "Hello, World" Applet:import java.applet.*; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello World", 25, 50); } } java.applet.Applet classFor creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.public void init(): is used to initialized the Applet. It is invoked only once.public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.public void destroy(): is used to destroy the Applet. It is invoked only once.java.awt.Component classpublic void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?Java Plug-in software. How to run an Applet?There are two ways to run an appletBy html file.By appletViewer tool (for testing purpose).

myapplet.html

Example of Applet by html file:To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file.

//First.javaimportjava.applet.Applet;importjava.awt.Graphics;publicclassFirstextendsApplet{publicvoidpaint(Graphicsg){g.drawString("welcome",150,150);}}

Example of Applet by appletviewer tool://First.javaimportjava.applet.Applet;importjava.awt.Graphics;publicclassFirstextendsApplet{ publicvoidpaint(Graphicsg){g.drawString("welcometoapplet",150,150);} }/**/

To execute the applet by appletviewer tool, write in command prompt:c:\>javac First.java c:\>appletviewer First.java

importjava.applet.Applet;importjava.awt.*;publicclassGraphicsDemoextendsApplet{publicvoidpaint(Graphicsg){g.setColor(Color.red);g.drawString("Welcome",50,50);g.drawLine(20,30,20,300);g.drawRect(70,100,30,30);g.fillRect(170,100,30,30);g.drawOval(70,200,30,30);g.setColor(Color.pink);g.fillOval(170,200,30,30);g.drawArc(90,150,30,30,30,270);g.fillArc(270,150,30,30,0,180);}}

OUTPUT Displaying Image in AppletSyntax of drawImage() method:

public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.

How to get the object of Image:The java.applet.Applet class provides getImage() method that returns the object of Image.

Syntax: publicImagegetImage(URLu,Stringimage){}

Other required methods of Applet class to display image:public URL getDocumentBase(): is used to return the URL of the document in which applet is embedded.

public URL getCodeBase(): is used to return the base URL.

importjava.awt.*;importjava.applet.*;publicclassDisplayImageextendsApplet{Imagepicture;publicvoidinit(){picture=getImage(getDocumentBase(),"sonoo.jpg");}publicvoidpaint(Graphicsg){g.drawImage(picture,30,30,this);}}

OUTPUT

Getting Applet Parameters:We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method named getParameter().

Syntax:publicStringgetParameter(StringparameterName)

importjava.applet.Applet;importjava.awt.Graphics;publicclassUseParamextendsApplet{publicvoidpaint(Graphicsg){Stringstr=getParameter("msg");g.drawString(str,50,50);}}

OUTPUT Animation in applet:importjava.awt.*;importjava.applet.*;publicclassAnimationExampleextendsApplet{Imagepicture;publicvoidinit(){picture=getImage(getDocumentBase(),"bike_1.gif");}publicvoidpaint(Graphicsg){for(inti=0;i Click on advanced tab then environment variables -> Click on the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable value -> ok -> ok -> ok.

After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin. Note: There are two types of tomcat available: Apache tomcat that needs to extract only (no need to install)Apache tomcat that needs to install

How to change port number of apache tomcatChanging the port number is required if there is another server running on the same system with same port number.Suppose you have installed oracle, you need to change the port number of apache tomcat because both have the default port number 8080.Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by 9999 and save this file.

How to deploy the servlet projectCopy the project and paste it in the webapps folder under apache tomcat.

But there are several ways to deploy the project. They are as follows:By copying the context(project) folder into the webapps directoryBy copying the war folder into the webapps directoryBy selecting the folder path from the serverBy selecting the war file from the server

Here, we are using the first approach.You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write:projectfolder>jarcvfmyproject.war*Creating war file has an advantage that moving the project from one location to another takes less time.

6. How to access the servletOpen broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:http://localhost:9999/demo/welcome

JDBC JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.

Making a connection to a database.Creating SQL or MySQL statements.Executing SQL or MySQL queries in the database.Viewing & Modifying the resulting records.

JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as Java ApplicationsJava AppletsJava ServletsJava ServerPages (JSPs)Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data.JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.

JDBC ArchitectureThe JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers JDBC API: This provides the application-to-JDBC Manager connection.JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

Common JDBC ComponentsThe JDBC API provides the following interfaces and classes DriverManager: This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.Connection: This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.

Statement: You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.SQLException: This class handles any errors that occur in a database application.

Creating JDBC ApplicationThere are following six steps involved in building a JDBC application:Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

//STEP 1. Import required packagesimport java.sql.*;

public class FirstExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last");

//Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!");}//end main}//end FirstExample OutputConnecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: KhanID: 103, Age: 28, First: Sumit, Last: Mittal