Você está na página 1de 36

TABLE OF CONTENTS

1. Introduction of JAVA 2. JVM 3. JRE 4. Concept of OOPs 5. Classes & Object 6. Interface 7. Constructor 8. This Pointer 9. Exception Handling 10.Multithreading 11.Applet 12.AWT 13.Event Handling 14.Swing 15.Servlets 16.Session 17.JSP

JAVA
Java is a programming language developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, classbased, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere." Java is currently one of the most popular programming languages in use, particularly for clientserver web applications. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies.

JDK 1.0 (January 23, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 (December 8, 1998) J2SE 1.3 (May 8, 2000) J2SE 1.4 (February 6, 2002) J2SE 5.0 (September 30, 2004) Java SE 6 (December 11, 2006) Java SE 7 (July 28, 2011)

JAVA VIRTUAL MACHINE (JVM)


A Java virtual machine (JVM) is a virtual machine capable of executing Java bytecode. A JVM provides an environment in which Java bytecode can be executed, enabling such features as automated exception handling, which provides "root-cause" debugging information for every software error, independent of the source code. A JVM is distributed along with APIs bundled together form the Java Runtime Environment (JRE). JVMs are available for many hardware and software platforms. The use of the same bytecode for all JVMs on all platforms allows Java to be described as a "write once, run anywhere" programming language, as opposed to "write once, compile anywhere", which describes crossplatform compiled languages. Thus, the JVM is a crucial component of the Java platform. Java bytecode is an intermediate language which is typically compiled from Java, but it can also be compiled from other programming languages.

JAVA RUNTIME ENVIRONMENT


Sun Microsystem's Java execution environment is termed the Java Runtime Environment, or JRE.Programs intended to run on a JVM must be compiled into a standardized portable binary

format, which typically comes in the form of .class files. A program may consist of many classes in different files. For easier distribution of large programs, multiple class files may be packaged together in a .jar file. The JVM runtime executes .class or .jar files, emulating the JVM instruction set by interpreting it, or using a just-in-time compiler (JIT) such as Oracle's HotSpot. JIT compiling, not interpreting, is used in most JVMs today to achieve greater speed.

OBJECT ORIENTED CONCEPTS IN JAVA


Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other.These include class, method, inheritance, encapsulation, abstraction, polymorphism etc. ENCAPSULATION This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process.

CLASS & OBJECT


Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group termed as a class. All the objects are direct interacted. Object is the feature of a class which is used for the working on the particular properties of the class. Objects are the basic run time entity or in other words object is a instance of a class. Example:Class Abc { public void display() { System.out.print( Base); } public static void main(String args[]) { Abc ob = new Abc(); // object created ob.display(); ob.show(); } }

INHERITANCE
Inheritance is a mechanism that enables one class to inherit all the behavior and attributes of another class. A class that inherits from another class is called a subclass, and the class from which inheritance takes place is called a superclass. Types of Inheritance in java:1.Single inheritance. 2.Multilevel inheritance. 3. Hierarchical inheritance . Java also support multiple inheritance but with the help of interfaces. SINGLE INHERITANCE When a subclass is derived simply from it's parent class is known as single inheritance. In case of single inheritance there is only a sub class and it's parent class. It is also called simple inheritance. Example:Class abc { public void display()

{ System.out.print( Base); } } Class def extends abc { public void show() { System.out.print( Derived); } } Class pqr { public static void main(String args[]) { def ob = new def(); ob.display(); ob.show(); } } MULTILEVEL INHERITANCE When a subclass is derived from a derived class is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's parent class. Multilevel inheritance can go up to any number of level. Example:class A { int x; int y; int get(int p, int q) { x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A { void Showb() { System.out.println("B");

} } class C extends B { void display() { System.out.println("C"); } public static void main(String args[]) { A a = new A(); a.get(5,6); a.Show(); }} HIERARCHICAL INHERITANCE In case of hierarchical inheritance we derive more than one subclass from a single super class. Example:class one { int x=10,y=20; void display() { System.out.println("This is the method in class one"); System.out.println("Value of X= "+x); System.out.println("Value of Y= "+y); } } class two extends one { void add() { System.out.println("This is the method in class two"); System.out.println("X+Y= "+(x+y)); } } class three extends one { voidmul()

{ System.out.println("This is the method in class three"); System.out.println("X*Y= "+(x*y)); } } classHier { public static void main(String args[]) { two t1=new two(); three t2=new three(); t1.display(); t1.add(); t2.mul(); } } MULTIPLE INHERITANCE The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.

INTERFACE
An interface is basically a kind of class that contains abstract methods, means that interface do not specify any code to implement these methods and data fields contain only constants.With the interface we can show the multiple inheritance in java.We can extends one class as well as implement interface.Two interfaces can extend to each other.If we implement a interface and that is extend by other interface so we have to implement both interface in class. IMPLEMENTING MULTIPLE INHERITANCE:public interface Payable { final double NOTHING = 0.0; abstract double calculateSalary(); } abstract class Employee implements Payable { // Remainder of class definition abstract double calculateSalary(); } class Contractor implements Payable {

Boolean contractCompleted = false; Double calculateSalary() { double salary; if (contractCompleted) { salary = 15000.00; } else { salary = NOTHING; } return salary; } } IMPLEMENTING INTERFACE:Class student {int rollno; Void getno(int n) { Rollno=n; } Void putno() { System.out.print(rollno: + rollno); }} Class test extends student { Float part1,part2; Void getmarks(float m1,float m2) { part m=m; part=m; } Void putmarks() { System.out.print(marks obtained); System.out.print(part= +part); }} Interface sports { float sportwt=6.of; Void putwt(); } Class result extends test implement sports {

float total; Public void putwt() { System.out.print(sports wt = + sportwt); }} Class hybrid { public ststic void main(String args[]) { results student= new results(); Student.getno(4564); Student getmarks(45.5H , 55.oF); }

POLYMORPHISM
Polymorphism means "same thing will exists with different forms. This is one of the basic principles of object oriented programming. Polymorphism are mainly two types:1.Static polymorphism(Compile time) 2.Dynamic polymorphism(Run time) STATIC POLYMORPHISM(COMPILE TIME) The method overloading is compiletime polymorphism. In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.Overloaded methods are always the part of the same class. These methods have the same name, but they may take different input parameters. Example:Class overLoading { public static void main(String[] args) { functionOverload obj = new functionOverload(); obj.add(1,2); obj.add(\"Life at \", \"?\"); obj.add(11.5, 22.5); } } class functionOverload { /* void add(int a, int b) { int sum = a + b; System.out.println(\"Sum of a+b is \"+sum); } */ void add(int a, int b, int c)

{ int sum = a + b + c; System.out.println(\"Sum of a+b+c is \"+sum); } void add(double a, double b) { double sum = a + b; System.out.println(\"Sum of a+b is \"+sum); } void add(String s1, String s2) { String s = s1+s2; System.out.println(s); } } DYNAMIC POLYMORPHISM (RUNTIME) The method overriding is runtime polymorphism. A method in subclass overrides the method in its super classes with the same name and signature. JVM determines the proper method to call at the runtime, not at the compile time. Example:class Animal { void abc() { System.out.println("A generic Animal."); } } class Dog extends Animal { void abc() { System.out.println("A Dog."); } } Class RuntimePolymorphismDemo { public static void main(String[] args) { Animal ref1 = new Animal(); Animal ref2 = new Dog();

ref1.abc(); ref2.abc(); } }

ABSTRACTION
Abstraction is nothing but data hiding.It involves with the dealing of essential information of a particular object or a concept and hide the other information. Example:public class Animal extends LivingThing { private Location loc; private double energyReserves; booleanisHungry() { returnenergyReserves< 2.5; } void eat(Food f) { energyReserves += f.getCalories(); } void moveTo(Location l) { loc = l; } } public static void main(String[] args) { theRat = new Animal(); theCat = new Animal(); if (theRat.isHungry()) { theRat.eat(tableScraps); } if (theCat.isHungry()) { theCat.eat(grass); } theCat.moveTo(theBarn); }

CONSTRUCTORS
Every class has at least one its own constructor. Constructor creates a instance for the class. Constructor initiates something related to the class's methods. Constructor is the method which name is same to the class. Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Example:class another { int x,y; another(int a, int b) { x = a; y = b; } another() { } int area() { int ar = x*y; return(ar); } } public class Construct { public static void main(String[] args) { another b = new another(); b.x = 2; b.y = 3; System.out.println("Area of rectangle : " + b.area()); System.out.println("Value of y in another class : " + b.y); another a = new another(1,1); System.out.println("Area of rectangle : " + a.area()); System.out.println("Value of x in another class : " + a.x); } } DEFAULT CONSTRUCTOR

There is always atleast one constructor in every class. If the programmer does not supply any constructor the compiler generates a default constructor automatically and takes no arguments. Example:public class Employee { String employee Name, employee Address; public Employee() { employee Name= abc; employee Address = xyz; } public void displayDetail() { System.out.println(Name of an employee:+employee Name); System.out.println(Address of an employee:+employee Address); } public static void main(String args[]) { Employee obj = new Employee(); obj.displayDetail(); } } COPY CONSTRUCTOR A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter. Example:public final class Galaxy { public Galaxy (double aMass, String aName) { fMass = aMass; fName = aName; } public Galaxy(Galaxy aGalaxy) { this(aGalaxy.getMass(), aGalaxy.getName()); } public static Galaxy newInstance(Galaxy aGalaxy) { return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());

} public double getMass() { returnfMass; } public void setMass( double aMass ) { fMass = aMass; } public String getName() { returnfName; } private double fMass; private final String fName; public static void main (String... aArguments) { Galaxy m101 = new Galaxy(15.0, "M101"); Galaxy m101CopyOne = new Galaxy(m101); m101CopyOne.setMass(25.0); System.out.println("M101 mass: " + m101.getMass()); System.out.println("M101Copy mass: " + m101CopyOne.getMass()); Galaxy m101CopyTwo = Galaxy.newInstance(m101); m101CopyTwo.setMass(35.0); System.out.println("M101 mass: " + m101.getMass()); System.out.println("M101CopyTwo mass: " + m101CopyTwo.getMass()); } } CONSTRUCTOR OVERLOADING Whenever we assign the name of the method same as class name. Remember this method should not have any return type. This is called as constructor overloading. Example:class Rectangle { int l, b; float p, q; public Rectangle(int x, int y) { l = x; b = y;

} public int first() { return(l * b); } public Rectangle(int x) { l = x; b = x; } public Rectangle(float x) { p = x; q = x; } public float third() { return(p * q); } public Rectangle(float x, float y) { p = x; q = y; } } public class ConstructorOverloading { public static void main(String args[]) { Rectangle rectangle1=new Rectangle(2,4); int areaInFirstConstructor=rectangle1.first(); System.out.println(" The area of a rectangle in first constructor is : "+areaInFirstConstructor); System.out.println(" The area of a rectangle in first constructor is : "+areaInSecondConstructo r); Rectangle rectangle3=new Rectangle(2.0f); float areaInThirdConstructor=rectangle3.third(); System.out.println(" The area of a rectangle in first constructor is : "+areaInThirdConstructor); Rectangle rectangle4=new Rectangle(3.0f,2.0f); float areaInFourthConstructor=rectangle4.fourth(); System.out.println(" The area of a rectangle in first constructor is : "+ areaInFourthConstruct or); } }

THIS POINTER
It is a special type of pointer which contain the address of class and holds the address of the activated object. Example Class bulb { int w; public vod set(int a) { W=a; System.out.print(w); } } Class psp { Public static void main(string args[]) { bulb b=new bulb; b.set(65); } }

MULTITHREADING
Multithreading is a conceptual programming paradigm where program is divided into two parts, which can be implemented at the same time. Each part of such program I called a Threadand each thread defins a separate parts for execution.Multithreading is a special form of multitasking. CREATING A THREAD:1. By extending thread class. Class mythread extends Thread { mytherad(String name) { super(name); start(); } } Public void run() { for( i=4; i<=5; i++) System.out.print(name is:+Thread.currentThread().getname()); Try { Therad.sleep(45); } catch(Exeption e){} } } class psp { public static void main(String args[]) { Mythread m=new mythraed(Thread I) Mythread m=new mythraed(Thread II) } } 2. by implementing running interface. Class mythread implements Runnable { mythread(String name) {Thread T=new Thread(name this); T.statr() } }

Public void run() { for( i=4; i<=5; i++) System.out.print(name is:+Thread.currentThread().getname()); Try { Therad.sleep(45); } catch(Exeption e){} } } class psp { public static void main(String args[]) { Mythread m=new mythraed(Thread I) Mythread m=new mythraed(Thread II) } }

EXEPTION HANDLING
An exception is a condition that occurs due to a runtime error in the program. It is a logical error that is generated at the runtime. If we want to continue with the execution of the remaining code, then we shoud try to catch the exception object thrown by the error condition and then display an appropriate msg for taking corrective action. This is known EXCEPTION HANDLING.
Exception type ArithmaticException ArrayIndexOutOfBoundException ArrayStoreExcpetion FileNotFoundException IOException Cause of exception Caused by math error Caused by Bada array index

Caused by Prog. Tries to store wrong type of data Caused by File not exists. Caused by I/O failure

Exception can be handled by:-Try, Catch, Final, Throw

Example:class exhandle { public static void main(String args[]) {int a[ ]={5,10};

Int b=5; Try { int x=a[2]/b-a[1]; }

Catch(ArithmaticExeception e) { } Catch(ArrayIndexOutOfBoundException e) { System.out.println(array index error); } Catch (ArrayStoreExeception e) { System.out.println(wrong data type); } int y=a[1]/a[0] system.out.println(y= +y); } } System.out.println(divide by zero);

APPLET
Java applets can run in a Web browser using a JVM, Applet viewer, a stand-alone tool for testing Applets. An Applet is a special Java program that can be embedded in HTML documents. It is automatically executed by web browsers. Applets are used to provide interactive features to web applications that cannot be provided by HTML alone

ELEMENTS OF APPLETS
1. 2. 3. 4. Superclass: java.applet.Applet No main method paint method to paint the picture Applet tag: <applet> </applet> 1. code 2. width and height

JAVA CLASSES FOR APPLET

This is the hierarchical representation of java classes. These classes are used to create Applet. The Applet class extends from panel which further extends from container, component and object classes.

LIFE-CYCLE OF APPLET
1. Initialization :- init() called exactly once in an applets life. It is called when an Applet is first loaded, which is after object creation. Used to read applet parameters, start downloading any other images or media files, etc. 2. Starting:- start() is called at least once. Called when an Applet is started or restarted i.e., whenever the browser visits the web page.
3. Stopping:- stop() is called when the browser leaves the web page.

4. Destroying: - stop() called when the browser unloads the Applet. It is used to perform any final clean-up. 5. Painting:-This is the way applet actually draws something on screen, paint() is used.

Example
import java.awt.*; import java.applet.*; public class HelloApplet extends Applet { public void init() { setBackground(Color.black); System.out.println("init() method invoked"); } public void start() { System.out.println("start() method invoked"); } public void paint( Graphics g ) { System.out.println("paint() method invoked"); g.drawString( "Hi there", 24, 25 ); } public void stop() { System.out.println("stop() method invoked"); } }

AWT
The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit. The AWT is now part of the Java Foundation Classes (JFC) the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles.

THE WINDOW FUNDAMENTALS:1. COMPONENTS:Modern user interfaces are built around the idea of components reusable gadgets that implement a specific part of the interface.AWT comes with a repertoire of basic user interface components, along with the machinery for creating your own components. 1. Static Text The Label class provides a means to display a single line of text on the screenThey provide visual aids to the user: for example, you might use a label to describe an input field. 2. User Input Java provides several different ways for a user to provide input to an application. The user can type the information or select it from a preset list of available choices. 1. TextField and TextArea classes:Two components are available for entering keyboard input: TextField for single line input and TextArea for multi-line input. 2. Checkbox classes:Checkbox which lets you select or deselect an option. checkbox for a Dialog option. Clicking on the box selects the option and makes the box change appearance. A second click deselects the option. 3. The Choice class:The Choice class was designed to use screen space more efficiently. When a Choice element is displayed on the screen, at any time, only one item in a Choice may be selected, so selecting an item implicitly deselects everything else. 4 The List class:Somewhere between Choice and CheckboxGroup in the screen real estate business is a component called List. With a List, the user is still able to select any item. 5. Menus:Java menus look like the menus in the windowing environment under which the program runs. Currently, menus can only appear within a Frame, although this will probably change in the future. 6. The Scrollbar class:-

Most people are familiar with scrollbars. Selecting or moving the scrollbar triggers an event that allows the program to process the scrollbar movement and respond accordingly. 7. The Button class:A button is little more than a label that you can click on. Selecting a button triggers an event telling the program to go to work.

2. CONTAINERS:A Container is a type of component that provides a rectangular area within which other components can be organized by a LayoutManager. Because Container is a subclass of Component, a Container can go inside another Container, which can go inside another Container.

3. PANELS:A Panel is the basic building block of an Applet. It provides a container with no special features. The default layout for a Panel is FlowLayout. Other objects can be added to panel by its add() method. You can resize using the set location(), set size () etc.

4. WINDOWS:A Window provides a top-level window on the screen, with no borders or menu bar. It provides a way to implement pop-up messages, among other things. The default layout for a Window is BorderLayout.

5. FRAMES
A frame is a window with a title bar and a border. The Frame class is a subclass of Container class. Container class objects may have other components (e.g. Buttons) added to them using the add method A typical Java GUI will create and display one or more framesTo make a frame visible the message setVisbible(true) must be sent to the frame.

VARIOUS LAYOUT MANAGERS:1. Flow Layout:- A Default frame layout and components are placed on new line only when needed. 2. Grid Layout:- Frame is declared as a grid of fixed size (e.g. two rows and three columns).Components are placed in the grid left to right and top to bottom. 3. Border Layout:- Frame is divided into north, south, east, west, and center. Components are placed by the programmer in the desired location using the add method.

EVENT HANDLING
Like most windows programming environments, AWT is event driven. When an event occurs (for example, the user presses a key or moves the mouse), the environment generates an event and passes it along to a handler to process the event. If nobody wants to handle the event, the system ignores it

DELEGATION EVENT MODEL


1. Event classes is the component with which user interacts.

2. Event object is created and contains information about the event that happened. 3. Event listener is notified when an event happens.

EVENT CLASSES
Defined by AWT are as follows:Inside java.awt.AWTEvent contains following :1. 2. 3. 4. 5. java.awt.event.ComponentEvent (component resized, moved, etc.) java.awt.event.FocusEvent (component got focus, lost focus) java.awt.event.InputEvent java.awt.event.KeyEvent (component got key-press, key-release, etc.) java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)

EVENT LISTENERS
An EventListener interface will typically have a separate method for each distinct event type the event class represents. Defined by the combination of an Event class paired with a particular method in an EventListener. java.util.EventListener consist of:1. java.awt.event.ComponentListener 2. java.awt.event.ContainerListener 3. java.awt.event.FocusListener 4. java.awt.event.KeyListener 5. java.awt.event.MouseListener 6. java.awt.event.MouseMotionListener

EVENT SOURCES
Because the events fired by an event source are defined by particular methods on that object, it is completely clear from the API documentation exactly which events an object supports.

1. java.awt.Component addComponentListener(ComponentListener l) addFocusListener(FocusListener l) addKeyListener(KeyListener l) addMouseListener(MouseListener l) addMouseMotionListener(MouseMotionListener l) 2. java.awt.Container addContainerListener(ContainerListener l) 3. java.awt.Dialog addWindowListener(WindowListener l) 4. java.awt.Frame addWindowListener(WindowListener l) 5. java.awt.Button addActionListener(ActionListener l)

ADAPTER CLASSES
Since many of the EventListener interfaces are designed to listen to multiple event subtypes (i.e. the MouseListener listens to mouse-down, mouse-up, mouse-enter, etc.), the AWT will provide a a set of abstract "adapter" classes, one which implements each listener interface. The Adapter classes provided by AWT are as follows: 1. 2. 3. 4. java.awt.event.FocusAdapter java.awt.event.KeyAdapter java.awt.event.MouseAdapter java.awt.event.MouseMotionAdapter

import java.awt.*; import java.awt.event.*; public class SimpleAWT extends java.applet.Applet implements ActionListener, ItemListener { private Button button = new Button("Push Me!"); private Checkbox checkbox = new Checkbox("Check Me!"); private Choice choice = new Choice(); private Label label = new Label("Pick something!"); public void init() {

button.addActionListener(this); checkbox.addItemListener(this); choice.addItemListener(this); // An Applet is a Container because it extends Panel. setLayout(new BorderLayout()); choice.addItem("Red"); choice.addItem("Green"); choice.addItem("Blue"); Panel panel = new Panel(); panel.add(button); panel.add(checkbox); panel.add(choice); add(label, "Center"); add(panel, "South");
}

public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setText("The Button was pushed."); } } public void itemStateChanged(ItemEvent e) { if (e.getSource() == checkbox) { label.setText("The Checkbox is now " + checkbox.getState() + "."); } else if (e.getSource() == choice) { label.setText(choice.getSelectedItem() + was selected.); }

SWING
Swing is the primary Java GUI toolkit. It is part of Oracle's JFC an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit.Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. SWING ARCHITECTURE Swing is a platform-independent, Model-View-Controller GUI framework for Java. It follows a single-threaded programming model, and possesses the following traits. Extensible:-Swing is a highly partitioned architecture, which allows for the "plugging" of various custom implementations of specified framework interfaces: Users can provide their own custom implementation(s) of these components to override the default implementations. Configurable:-Swing's heavy reliance on runtime mechanisms and indirect composition patterns allows it to respond at runtime to fundamental changes in its settings. Lightweight:-Swing's configurability is a result of a choice not to use the native host OS's GUI controls for displaying itself. Swing "paints" its controls programmatically through the use of Java 2D APIs, rather than calling into a native user interface toolkit. Loosely-Coupled:-The Swing library make use of the Model/Vie software design pattern which conceptually decouples the data being viewed from the user interface controls through which it is viewed.

Example
import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class SwingExample { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame f = new JFrame("Swing Example Window"); f.setLayout(new FlowLayout()); f.add(new JLabel("Hello, world!")); f.add(new JButton("Press me!")); f.pack(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setVisible(true); } } }

TOMCAT
A popular Java servlet container from the Apacheproject. Tomcat uses the Jasper converter to turn JSPs into servlets for execution. Tomcat is widely used with the application server. Tomcat provides local server.Apache Jakarta Tomcat--or just Tomcat--is one of those projects Tomcat is a container for servlets:Tomcat can act as a simple standalone server for Web applications that use HTML, servlets, and JSP Apache is an industrial-strength, highly optimized server that can be extended with Tomcat

Tomcat

C:\tomcat7
extract (delete folder)

bin startup.bat edit

TO SET THE PATH:SET CATALINA_HOME=C:\tomcat7 SET JAVA_HOME=C:\jdk1.6 Now double click on startup.bat , if the window will stop then the path is not set & if it will show the window then the path is set. GUIDELINES:-Tomcat7,Webapps , Create first.com, Create WEB-INF + store html files, Classes + store xml files, Servelets (.classfile) HTML CODING <html> <head> <title> Servelet </title> </head> <body> <form action =/first.com/aa>name<input type=text name =nm> <br> City<input type =text name=ct> <br> <input type =submit value =select> </form> </body></html>

SESSION
A session is a concept that represents a series of HTTP requests and responses between a specific browser and a specific server. Sessions are managed by the server. Created by the server when the first request is received from a browser on a new host the server starts the session and assigns it an ID.

WHY SHOULD A SESSION BE MAINTAINED


When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests because HTTP is a stateless protocol.When there is a need to maintain the conversational state, session tracking is needed.

SESSION TRACKING METHODS


User authorization Hidden fields URL rewriting Cookies
The first four methods are traditionally used for session tracking in all the server-side technologies.

1. User Authorization
Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields
<INPUT TYPE=hidden NAME=technology VALUE=servlet>

Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers.

3. URL Rewriting
Original URL: http://server:port/servlet/ServletName Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456 When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session.

4. Cookies
Cookies are the mostly used technology for session tracking, key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Cookie cookie = new Cookie(userID, 7456); res.addCookie(cookie);

JSP
Mostly HTML page, with extension .jsp Include JSP tags to enable dynamic content creation Translation: JSP Servlet class Compiled at Request time (first request, a little slow) Execution: Request JSP Servlet's service method. <%@ Directive %> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

<%-- JSPComment -->


<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" /> </body> </html>

Template Text
<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value="${1 + 2 + 3}" />

</body> </html> <%= expr> Java expression whose output is spliced into HTML <%= userInfo.getUserName() %> <%= 1 + 1 %> <%= new java.util.Date() %> Translated to out.println(userInfo.getUserName()) ... <% code %> Scriptlet :Add a whole block of code to JSP, passed through to JSP's service method. <%@ page language="java" contentType="text/html" %> <%@ page import="java.util.*" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <% // Create an ArrayList with test data ArrayList list = new ArrayList( ); Map author1 = new HashMap( ); author1.put("name", "John Irving"); author1.put("id", new Integer(1)); list.add(author1); Map author2 = new HashMap( ); author2.put("name", "William Gibson"); author2.put("id", new Integer(2)); list.add(author2); Map author3 = new HashMap( ); author3.put("name", "Douglas Adams"); author3.put("id", new Integer(3)); list.add(author3); pageContext.setAttribute("authors", list); %> <html> <head> <title>Search result: Authors</title> </head> <body bgcolor="white"> Here are all authors matching your search critera: <table> <th>Name</th> <th>Id</th> <c:forEach items=${authors} var=current> <%@ page language="java" contentType="text/html" %> <html> <head> <title>Browser Check</title> </head> <body bgcolor="white"> <%

String userAgent = request.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") != -1) { %> You're using Internet Explorer. <% } else if (userAgent.indexOf("Mozilla") != -1) { %> You're probably using Netscape. <% }else { %> You're using a browser I don't know about. <% } %> </body> </html>

<%! decl> Turned into an instance variable for the servlet What did I tell you about instance variables & multithreaded servlets.
<%@ page language="java" contentType="text/html" %> <%! intglobalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor="white"> This page has been visited: <%= ++globalCounter %> times. <p> <% intlocalCounter = 0; %> This counter never increases its value: <%= ++localCounter %> </body> </html> Declarations have serious multithreading issues! <%@ page language="java" contentType="text/html" %> <%! intglobalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor="white"> This page has been visited: <%= ++globalCounter %> times. <p> <% intlocalCounter = 0;

%> This counter never increases its value: <%= ++localCounter %> </body> </html> <%@ page language="java" contentType="text/html" %> <%@ page import="java.util.Date" %> <%! intglobalCounter = 0; java.util.DatestartDate; public void jspInit( ) { startDate = new java.util.Date( ); } public void jspDestroy( ) { ServletContext context = getServletConfig().getServletContext( ); context.log("test.jsp was visited " + globalCounter + " times between " + startDate + " and " + (new Date( ))); } %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor="white"> This page has been visited: <%= ++globalCounter %>times since<%= startDate %>. </body> </html>

<jsp:include > <jsp:include page="trailer.html flush="true" />

SERVLET
A servlet is like an applet, but on the server side.Units of Java code that run server-side. Run in containers (provide context). Helps with client-server communications Not necessarily over HTTP and But usually over HTTP.

WHY ARE SERVLETS


Web pages with dynamic content. Easy coordination between Servlets to make Web applications. The Containers support many features. Sessions, persistence, resource management (e.g., database connections), security etc.

import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*; public class Hellox extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throwsIOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); // out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } // doGet } // Hellox

XML CODING
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <description>Examples</description> <display-name>Examples</display-name> <servlet> <servlet-name>Hellox</servlet-name> <servlet-class>Hellox</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hellox</servlet-name> <url-pattern>/Hellox</url-pattern> </servlet-mapping></web-app> public class Helloy extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throwsIOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>");

out.println("<body>"); out.println("<head>"); out.println("<title>Hello, Tell me your name!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello, Tell me your name!</h1><br>"); out.print("<form action=\""); out.println("NamedHello\" method=POST>"); out.println("<input type=text length=20 name=yourname><br>"); out.println("<input type=submit></form>"); out.println("</body>"); out.println("</html>"); } } public class NamedHello extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throwsIOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("yourname"); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello, Tell me your name again!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h2>Hello, " + name + "</h2><br>"); out.print("<form action=\""); out.println("NamedHello\" method=POST>"); out.println("<input type=text length=20 name=yourname><br>"); out.println("<input type=submit></form>"); out.println("</body>"); out.println("</html>"); }} public class NamedSessionHello1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throwsIOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSessionhs = request.getSession(true); String sn = (String) hs.getAttribute("yourname"); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello, Tell me your name again!</title>"); out.println("</head>"); out.println("<body>"); if(sn != null && ! sn.equals ("")) {

out.println("<h1><blink> OH, NamedSessionHello1 + already know your name: " + sn + "</blink></h1>"); } else { String sn2 = request.getParameter("yourname"); if (sn2 == null || sn2.equals("")) { out.println("<h2>Hello,noname " + "</h2><br>"); } else { out.println("<h2>Hello, " + sn2 + "</h2><br>"); hs.setAttribute("yourname", sn2); }} out.print("<form action=\""); out.println("NamedSessionHello2\" method=GET>"); ... }

Você também pode gostar