Anda di halaman 1dari 260

ADV Java

For [ TYBSC IT Sem V ]

Architecture Of Java
JVM JRE GC

Java platform
The Java platform consists of the Java application programming interfaces (APIs) and the Java virtual machine (JVM).

Java Program

Complier

ByteCode

JIT

Executable

Program Structure

General Form of Class

class classname { Fields (value types,Reference Type) Methods interface class }

General Form of Interface

Interface name { Methods }

Inheritance
Class Based Interface Based

Class-Based Inheritance
Concrete Class Abstract Class Object Class Multiple Inheritance is not supported

Interface-Based Inheritance
Achieve Multiple Inheritance. Solves Diamond Inheritance( Problem of c++.)

Nested-Class
A class that is declared within another class or interface, is called a nested class A top-level class or a top-level interface is one that is not nested can be beneficial if not used properly result in unreadable code.

http://java.sun.com/javase/downloads/ index_jdk5.jsp J2SE 5.0 Documentation download

Event Handling

EVENT

notify

generates register

LISTENER

Source

EVENT HANDLER

ActionEvent

ActionListener

Button

actionPerformed()

Class MyFrame extends JFrame implements ActionListener { MyFrame() { JButton jb=new JButton( show); Jb.addActionListener(this); add(jb); setSize(300,400); setVisible(true); } public void actionPerformed(ActionEvent ae) { System.out.println( show is clicked ); } }

Event ,Listener ,Handlers

ActionEvent ActionListener : actionPerformed()

Adapter-Class
simplify the creation of event handlers. provides an empty implementation of all methods in an event listener interface useful when to process only some of the events

AWT Hierarchy [java.awt]

Dialog

Applet

SWING
Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java. Prefix with J

SWING Hierarchy

Dialog

Frame

Applet

JComponent

JDialog

JFrame

JApplet

JPanel

JButton

Features of Swing
Platform-Independent. Light-Weight. [except Top-Level Container] Addition of New Components [JTree , JTable] Enhanced the capabilities of Regular components [Image on JButton]. Intermediate container Plug-N-Play. Better Look and Feel Pluggable Look And Feel. Transparent [ setOpaque()]

support of JRootPane UI-Delegates[model is separated from UI] Custom Models. Z-Order Addition of LayoutManagers Addition of Events,EventListener [javax.swing.event]

Coding difference

Components
Top-Level Container JFrame,JDialog,JWindow,JAppler Intermediate Container JPanel,JTabbedPane Atomic component JTree,JTable,JComboBox,JRadioButton

JFrame JFrame contains a JRootPane as its only child BorderLayout manager simply hide the JFrame. Use of setDefaultCloseOperation(int).

Constructor:
JFrame() JFrame(GraphicsConfiguration gc) JFrame(String title)

Fields
EXIT_ON_CLOSE HIDE_ON_CLOSE

Methods void update(Graphics g) void frameInit() Container getContentPane()

import javax.swing.*; class MyF extends JFrame { JButton jb1;Container c; MyF() { c=getContentPane(); jb1=new JButton( show ); c.add(jb1); setSize(300,400); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

Dialogs
A Dialog window is an independent subwindow meant to carry temporary notice apart from the main Swing Application Window . Every dialog is dependent on a Frame component

Standard Custom

JDialog Support of JRootPane. Use of ContentPane Custom dialogs BorderLayout Modal /Non-Modal []

Constructor JDialog() JDialog(Dialog owner)


JDialog(Dialog owner, String title, boolean modal)

JDialog(Frame owner)
JDialog(Frame owner, String title, boolean modal)

Field
Exit_ON_CLOSE

Methods void show(): void dialogInit() : void setJMenuBar(JMenuBar menu) :

import javax.swing.*; class MyD extends JDialog { JButton jb1;Container c; MyD(JFrame f) { super(f,My Dialog ,true); c=getContentPane(); jb1=new JButton( show ); c.add(jb1); setSize(300,400); } }

class MyF extends JFrame { MyD md; MyF() { md=new MyD(this); setSize(300,400); setVisible(true); md.show(); } }

JOptionPane standard dialog uses an internal frame

parameters to these methods


1 parentComponent 2 message 3 messageType
ERROR_MESSAGE INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE

PLAIN_MESSAGE

4 optionType
DEFAULT_OPTION YES_NO_OPTION YES_NO_CANCEL_OPTION OK_CANCEL_OPTION

Constructor
JOptionPane() JOptionPane(Object message, int messageType)

Fields:
CLOSED_OPTION ERROR_MESSAGE OK_OPTION

Import javax.swing.*; class MyO extends JFrame { MyO() { String n=JOptionPane.showInputDialog(this,enter name); setSize(300,400); setVisible(true); } }

JApplet
Signed/unsignedUnsigned-security restictions BorderLayout Java (Metal) look by default paintComponent, paint Double buffering turned on by default . Life Cycle similar to Applet Can have menus [JRootPane] All the benefits of swing container

http://java.sun.com/docs/books/tutorial/deployment/applet/

Constructor JApplet() Methods: getContentPane() setJMenuBar(JMenuBar menuBar) Fields: LEFT_ALIGNMENT, RIGHT_ALIGNMENT

import java.awt.*; import javax.swing.*;


/*<applet code = MyApplet width=300 height=200> </applet> */

public class MyApplet extends JApplet { public void paintComponents(Graphics g ) { g.drawRect(10, 20,200,40); } }

import javax.swing.*;import javax.swing.*; public class JAppletExample extends JApplet { Container c; public void init() { WindowUtilities.setNativeLookAndFeel(); c= getContentPane(); c.setBackground(Color.white); c.setLayout(new FlowLayout()); c.add(new JButton("Button 1")); c.add(new JButton("Button 2")); c.add(new JButton("Button 3")); }}

JPanel
JPanel is a generic lightweight container Defualt is FlowLayout opaque by default

replacement for Canvas double-buffering is turned on by default, ability to assign borders to JPanels [setBorder()]
The design of a complex user interface can be eased by the use of JPanels

Constructor: JPanel() JPanel(LayoutManager) Methods: void setLayout(LayoutManager) void add(Component) int getComponentCount() Component[] getComponents()

class P1 extends JPanel { JTextField t1;JButton jb1; P1() { t1=new JTextFiled(); b1=new JButton(); add(t1);add(b1); } }

class MyF extends JFrame { P1 p1; Container c; MyF() { c=getContentPane(); p1=new P1(); c.add(p1); } }

JTabbedPane
Tab representation A tabbed pane is a component that appears as a group of folders in a file cabinet Tabs/components are added to a TabbedPane object by using the addTab and insertTab methods

Constructor JTabbedPane() JTabbedPane(int tabPlacement) Fields JTabbedPane.TOP (default) JTabbedPane.RIGHT JTabbedPane.BOTTOM JTabbedPane.LEFT

Methods
void addTab(String title, Component component) void setSelectedIndex(int index) void addChangeListener(ChangeListener cl)

general procedure to use a tabbed pane

1. Create a JTabbedPane object. 2. Call addTab( ) to add a tab to the pane. 3. Repeat step 2 for each tab. 4. Add the tabbed pane to the content pane of the Top-Level Container.

class Tab extends JFrame { JTabbedPane tp; Container c; Tab() { c=getContentPane(); tp=new JTabbedPane(); tp.addTab(" first ",new P1()); tp.addTab(" second ",new P2()); c.add(tp); setSize(300,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) {new Tab(); }}

JScrollPane
Provides a scrollable view of a lightweight component

A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars constants are defined by the ScrollPaneConstants interface

Construcutor JScrollPane(Component comp) JScrollPane(int vsb, int hsb) JScrollPane(Component comp, int vsb, int hsb) Fields HORIZONTAL_SCROLLBAR_ALWAYS HORIZONTAL_SCROLLBAR_AS_NEEDED VERTICAL_SCROLLBAR_ALWAYS VERTICAL_SCROLLBAR_AS_NEEDED constants are defined by the ScrollPaneConstants interface

steps that you should follow to use a scroll pane Create a JComponent object. Create a JScrollPane object Add the scroll pane to the content pane of the applet

JTable
The JTable is used to display and edit regular twodimensional tables of cells. JTable does not contain or cache data; it is simply a view of your data Every table object uses a table model object to manage the actual table data. TableModelEvent , TableModelListener can set a type-specific cell renderer using the JTable method setDefaultRenderer The tool tip text displayed for a table cell is determined by the cell's renderer. Table sorting and filtering is managed by a sorter object.

steps for using a table

1. Create a JTable object. 2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.) 3. Add the table to the scroll pane. 4. Add the scroll pane to the content pane of the applet

String head[]={" Name "," Addr "," Tel No "}; String data[][]={{" 1 "," 1 "," 1 "},
{" 2 "," 2 "," 2 "}, {" 3 "," 3 "," 3 "}};

c=getContentPane(); jt=new JTable(data,head);


int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;

js=new JScrollPane(jt,v,h); c.add(js);

JComboBox A combo box is a compound component A component that combines a button or editable field and a drop-down list display a drop-down list that allows a user to select a different entry. Editable and Non-Editable combo box uses a combo box model

Constructor JComboBox() JComboBox(Object[]) JComboBox(Vector) Methods void insertItemAt(Object, int) void removeItemAt(int) void removeItem(Object) int getItemCount()

jcb=new JComboBox(); jcb.setEditable(true); jcb.addItem(" Maharashtra "); jcb.addItem(" Gujrath "); jcb.addItem(" Madhya Pradesh "); jcb.addItem(" Uttar Pradesh "); jcb.insertItemAt(" BIHAR ",1);

JList
A component that allows the user to select one or more objects from a list. Multiple Selections are possible JList doesn't support scrolling directly JScrollPane scrollPane = new JScrollPane(dataList); doesn't provide any special support for handling double or triple (or N) mouse cellRendererer, to paint the visible cells in the list uses an instance of ListSelectionModel to manage its selection.

There are three ways to create a list model: DefaultListModel everything is pretty much taken care of for you. The examples in this page use DefaultListModel. AbstractListModel you manage the data and invoke the "fire" methods. For this approach, you must subclass AbstractListModel and implement the getSize and getElementAt methods inherited from the ListModel interface. ListModel you manage everything.

Constructor JList(ListModel) JList(Object[]) JList(Vector) JList() Methods void setModel(ListModel) ListModel getModel() void addListSelectionListener(ListSelectionListener listener) int getSelectedIndex()

String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data); JScrollPane scrollPane = new JScrollPane(dataList);

JCheckBox
The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton

any number of check boxes in a group can be selected A check box generates ItemEvent and ActionEvent.

Constructor: JCheckBox(Icon i) JCheckBox(Icon i, boolean state) JCheckBox(String s) JCheckBox(String s, boolean state) JCheckBox(String s, Icon i) JCheckBox(String s, Icon i, boolean state) Methods: void addActionListener(ActionListener l) void addItemListener(ItemListener l) setBorderPaintedFlat(boolean b) void setSelected(boolean state)

JCheckBox cb = new JCheckBox("C", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this);

JRadioButton
Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. Swing radio buttons have all the usual button characteristics A JRadioButton generates ItemEvent and ActionEvent. For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. The ButtonGroup object is a logical grouping -- not a physical grouping

Constructor JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s) JRadioButton(String s, boolean state) JRadioButton(String s, Icon i) JRadioButton(String s, Icon i, boolean state) Methods void add(AbstractButton ab) void addActionListener(ActionListener l) void addItemListener(ItemListener l)

JRadioButton b1 = new JRadioButton("A"); JRadioButton b2 = new JRadioButton("B"); JRadioButton b3 = new JRadioButton("C"); ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); bg.add(b3);

JTree
A tree is a component that presents a hierarchical view of data. A user has the ability to expand or collapse individual subtrees in this display A JTree object does not actually contain your data; it simply provides a view of the data [Model] . Root Node, Branch Node, Leaf Node. A specific node in a tree can be identified by a TreePath.

The steps to use a tree


1. Create a JTree object. 2. Create a JScrollPane object. (The arguments to the constructor specify the treeand the policies for vertical and horizontal scroll bars.) 3. Add the tree to the scroll pane. 4. Add the scroll pane to the content pane of the applet.

Constructor JTree(Hashtable ht) JTree(Object obj[ ]) JTree(TreeNode tn) JTree(Vector v) Methods void add(MutableTreeNode child) void treeCollapsed(TreeExpansionEvent tee) void treeExpanded(TreeExpansionEvent tee) TreePath getPath( ) TreePath getPathForLocation(int x, int y) TreePath[] getSelectionPaths() TreeCellRenderer getCellRenderer() TreePath getAnchorSelectionPath()

top = new DefaultMutableTreeNode("Options"); a = new DefaultMutableTreeNode("A"); a1 = new DefaultMutableTreeNode("A1"); b = new DefaultMutableTreeNode(B"); b1 = new DefaultMutableTreeNode(B1"); a.add(a1);b.add(b1); top.add(a);top.add(b); tree = new JTree(top); JScrollPane jsp = new JScrollPane(tree, v, h);

Custom Rendering of JList Cells


A list uses an object called a cell renderer to display each of its items The default cell renderer invoks toString you can implement a custom cell renderer steps Write a class that implements the ListCellRenderer interface. Create an instance of your class and call the list's setCellRenderer using the instance as an argument.

Example
class MyCellRenderer extends JLabel implements ListCellRenderer { public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // code } } String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data); dataList.setCellRenderer(new MyCellRenderer());

JDBC

The Complete Guide to JAVA Database Programming, Matthew Siple, TMH

Introduction to JDBC
Lets programmers connect to a database, query it or update through a Java application. Programs developed with Java & JDBC are platform & vendor independent. JDBC library is implemented in java.sql package

JDBC

Driver

Oracle DB

Java Program

JDBC API

Driver SQL server DB MS-Access Driver DB

Advantages of JDBC
Leverage Existing Enterprise Data Simplified Enterprise Development - JDBC API is simple to learn, easy to deploy, and inexpensive to maintain. Zero Configuration for Network Computers

Key Features
Full Access to Metadata No Installation Database Connection Identified by URL Included in the Java Platform

JDBC Component/ Products


JDBC API [ DriverManager] JDBC-ODBC Bridge [Type -1 Driver] JDBC Test Suit

JDBC API Overview


The JDBC API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases The JDBC API provides a call-level API for SQLbased database access. Contains Interfaces and classes [Java.sql, javax.sql.]

JDBC API Overview


API layer has2 levels of interface. Application layer: developer uses API to make calls to DB via SQL & retrieve results. Driver layer : handles all communication with a specific Driver implementation. The JDBC API makes it possible to do three things: Establish a connection with a database or access any tabular data source Send SQL statements Process the results

Two-tier and Three-tier Models

Interfaces
Driver Connection Statement, PreparedStatement,CallableStatement ResultSet ResultSetMetaData DatabaseMetaData

JDBC API-Classes
Date DriverManager DriverPropertyInfo Time TimeStamp Types SQLException

Seven basic steps for db con.


import java.sql Load and Register Driver Make an Connection Create Statement Execute Statement Retrieve ResultSet Close statement and connection

Connection c;Statement stm try{ Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); c=DriverManager.getConnection(jdbc:odbc:emp); stm=c.createStatement(); stm.execute(create table employee (id varchar2(20))); c.close(); stm.close(); }catch(Exception e){S.o.p(e);}

Connection
A Connection object represents a connection with a database. standard syntax for JDBC URLs is jdbc:<subprotocol>:<subname> String url = "jdbc:odbc:wombat"; Connection con = DriverManager.getConnection(url, ad", "12Java"); A transaction consists of one or more statements that have been executed, completed, and then either committed or rolled back. When the method commit or rollback is called, the current transaction ends and another one begins

Sending SQL Statements 1 Statement- created by the Connection.createStatement method. 2 PreparedStatement-created by the Connection.prepareStatement 3 CallableStatement-created by the Connection.prepareCall method

void close() throws SQLException Statement createStatement() throws SQLException PreparedStatement prepareStatement(String sql) throws SQLException CallableStatement prepareCall(String sql) throws SQLException

Statements
The object used for executing a static SQL statement and returning the results it produces Sub interfaces are CallableStatement, PreparedStatement only one ResultSet object per Statement object can be open at the same time. Created by Connection.createStatement()

Methods of Statement boolean execute(String sql) throws SQLException int executeUpdate(String sql) throws
SQLException

ResultSet executeQuery(String sql) throws


SQLException

void close() throws SQLException

Statement PreparedStatement CallableStatement

PreparedStatement
An object that represents a precompiled SQL statement. This object can then be used to efficiently execute this statement multiple times. The setter methods (setShort, setString, and so on) are use for setting IN (? ) parameter values

Methods

boolean execute() throws SQLException int executeUpdate() throws SQLException ResultSet executeQuery() throws SQLException void close() throws SQLException

Example

String SQL = select * from Employees where First_Name=? PreparedStatement pstat = con.prepareStatement(sql); pstat.setString(1, John); ResultSet rs = pstat.executeQuery(); pstat.clearParameters();

CallableStatement
The interface used to execute SQL stored procedures. allows stored procedures to be called in a standard way Support IN,OUT,IN&OUT parameters IN set,Out -get

Methods
void close() throws SQLException
int getInt(int parameterIndex) throws SQLException long getLong(int parameterIndex) throws SQLException void setInt(String parameterName, int x) throws SQLException void setLong(String parameterName, long x) throws SQLException

CREATE OR REPLACE PROCEDUE sp_interest ( id IN INTEGER,bal IN OUT FLOAT ) AS BEGIN SELECT balance FROM accounts WHERE account_id = id ; bal := bal + bal * 0.03 ; UPDATE accounts SET balance = bal WHERE account_id = id ; END;

JDBC(stored procedure)
CallableStatement cstmt = con.prepareCall( { call sp_interest(?,?)} ); cstmt.setInt(1,accountID); cstmt.setFloat(2, 5888.86); cstmt.registerOutParameter(2,Types.FLOAT); cstmt.execute(); System.out.println(cstmt.getFloat(2));

ResultSet
A table of data representing a database result set A default ResultSet object is not updatable and has a cursor that moves forward only. provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row

ResultSet-Type Statement stmt = conn.createStatement(type, concurrency);


TYPE_FORWARD_ONLY TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE CONCUR_READ_ONLY CONCUR_UPDATEABLE

Methods
boolean next() throws SQLException ResultSetMetaData getMetaData() throws SQLException String getString(int columnIndex) throws SQLException void close() throws SQLException

String q=select * from employee while(rs.next()) { System.out.print(rs.getInt(1)); System.out.println(rs.getString(2)); }

ResultSetMetaData
An object that can be used to get information about the types and properties of the columns in a ResultSet object. ResultSetMetaData is a class which provides information about a result set that is returned by an executeQuery() method. Create by calling getMetaData() on ResultSet object.

Methods of ResultSetMetaData
int getColumnCount() throws SQLException String getColumnTypeName(int column) throws SQLException String getColumnName(int column) throws SQLException String getTableName(int column) throws SQLException

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); boolean b = rsmd.isSearchable(1);

DatabaseMetaData

DriverManager
Register the Driver class with the environment Make the connection with the database. Retrieve Connection object by calling getConnection method. The basic service for managing a set of JDBC drivers. Two types Two-Tier and Three Tier.

Methods of DriverManager
public static Connection getConnection(String url) throws SQLException public static Connection getConnection(String url, String user, String password) throws SQLException public static void registerDriver(Driver driver) throws SQLException public static void deregisterDriver(Driver driver) throws SQLException

Connection con; con=DriverManager.getConnection(jdbc:odbc:emp);

Swing & Jdbc

Types of Driver JDBC-ODBC Bridge (Type 1) Native-API partly Java Driver (Type 2) Net-Protocol All-Java Driver (Type 3) Native Protocol All-Java Driver (Type 4)

Type 1 Driver - JDBC-ODBC bridge

Java Application

JDBC DRIVER

DataBase

ODBC DRIVER TYPE-1 CLIENT-SIDE SERVER-SIDE

Advantages
Almost any database for which ODBC driver is installed, can be accessed. A type 1 driver is easy to install.

Disadvantages
Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native db connectivity interface. The ODBC driver needs to be installed on the client machine. Considering the client-side software needed, this is not suitable for applets.

Native-API partly Java Driver

(Type 2)

Java Application

JDBC DRIVER

DataBase

Vendor API TYPE-2 CLIENT-SIDE SERVER-SIDE

Advantages Better performance than Type 1 Driver (JDBC-ODBC bridge). Provides Fastest performance than all 3 drivers as it calls native APIs(MySQL,Oracle...etc). Disadvantages The vendor client library needs to be installed on the client machine. Not all databases have a client side library This driver is platform dependent This driver supports all java applications except Applets

Net-Protocol All-Java Driver (Type 3)


Java Application

MIDDLEWARE Vendor API TYPE-1 TYPE-2 TYPE-4

SERVER-SIDE

DataBase

JDBC DRIVER TYPE-3

CLIENT-SIDE

Advantages
database independent, there is no need for the vendor db library on the client machine. The Middleware Server (which can be a full fledged J2EE Application server) can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc. This driver supports Applets.

Disadvantages
Requires database-specific coding to be done in the middle tier. An extra layer added may result in a timebottleneck.

Native Protocol All-Java Driver

(Type 4)

Java Application

DataBase
JDBC DRIVER

TYPE-4 CLIENT-SIDE SERVER-SIDE

Advantages
enhance performance considerably. The JVM can manage all aspects of the application-todatabase connection; this can facilitate debugging. This driver supports Applets.

Disadvantages
Clients require a separate driver for each database. Drivers are database dependent.

What is HTML?
HTML is a language for describing web pages. HTML stands for Hyper Text Markup Language HTML is not a programming language, it is a markup language A markup language is a set of markup tags HTML uses markup tags to describe web pages

HTTP is a request response-based stateless protocol.

An HTTP message is any request from a client to a server, or any response from a server to a client. An HTTP message sent by a client to a server is called an HTTP request. The initial line for an HTTP request has three parts, separated by spaces: - A method name The local path of the requested resource (URI) The version of HTTP being used A typical request line is: GET /reports/sales/index.html HTTP/1.0

HTTP defines nine methods indicating the desired action to be performed on the identified resource

An HTTP message sent by a server to a client is called an HTTP response It has three parts, separated by spaces: the HTTP version, a response status code, English phrase describing the status code.
HTTP/1.0 200 OK Date: Tue, 01 Dec 2001 23:59:59 GMT Content-Type: text/html Content-Length: 52 <html><body> <h1>Hello, John!</h1> </body></html>

GET -Requests a representation of the specified resource. POST-Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. HEAD-Asks for the response identical to the one that would correspond to a GET request, but without the response body. PUT-Uploads a representation of the specified resource. DELETE-Deletes the specified resource. TRACE-Echoes back the received request, so that a client can see what (if any) changes or additions have been made by intermediate servers.

OPTIONS Returns the HTTP methods that the server supports for specified URL PATCH Is used to apply partial modifications to a resource.

CONNECT-Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL

Servlet
Objectives 1. Introduction to Servlet 2. Life Cycle of Servlet 3. Html Form Handling 4. Request Dispatching 5. Session Management/Tracking 6. Context Vs Config 7. Scope of an Attribute 8. DB Connectivity( Jdbc&Servlet ) 9. Synchronization in Servlet.

Static Content

Http Request HTML File WEB SERVER

Enter URL Browser Http Response

MIME-Multipurpose Internet Mail Extensions

Dynamic Content

Http Request

Enter URL Browser Http Response WEB SERVER

Program

CGI

P1

Browsers WEB SERVER

P2

Pn

Servlet Working

P1 S1 Browsers WEB SERVER

S2 WEB CONTAINER

Benefits of Servlet over CGI


performance is significantly better. Servlets execute within the address space of a Web server not necessary to create a separate process to handle each client request Servlets are platform-independent Java security manager on the server enforces a set of restrictions to protect the resources on a server The full functionality of the Java class libraries is available to a servlet

The Servlet API


Two packages contain the classes and interfaces that are required to build servlets. These are javax.servlet and javax.servlet.http. They constitute the Servlet API. Code that is loaded from a remote machine is untrusted Servlet. Trusted servlets are those which are loaded from the local machine. Unstrusted Servlet are restricted. There are two ways to create Servlet by extending

GenericServlet HttpServlet

Heirarchy Serializable Servlet ServletConfig GenericServlet HttpServlet

Servlet API- javax.servlet [Interfaces]


Servlet ServletConfig ServletContext ServletRequest ServletResponse Declares life cycle methods for a servlet. Allows servlets to get initialization parameters. access information about their environment. read data from a client request write data to a client response

SingleThreadModel Indicates that the servlet is thread safe

javax.servlet [classes]
GenericServlet ServletInputStream ServletOutputStream
Implements the Servlet and ServletConfig interfaces. Provides an input stream for reading requests from a client. Provides an output stream for writing responses to a client. Indicates a servlet error occurred.

ServletException

The Life Cycle of a Servlet


1. User enters a Uniform Resource Locator (URL) 2. HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server. 3. The server invokes the init( ) method of the servlet. 4. the server invokes the service( ) method of the servlet. This method is called to process the HTTP request The servlet remains in the servers address space and is available to process any other HTTP requests received from clients. 5 . The server may decide to unload the servlet from its memory.

Servlet Life Cycle


The life cycle of a servlet is controlled by the container in which the servlet has been deployed When a request is mapped to a servlet, the container performs the following steps. If an instance of the servlet does not exist, the Web container Loads the servlet class. Creates an instance of the servlet class.

Initializes the servlet instance by calling the init method Invokes the service method, passing a request and response object If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.

Initializing a Servlet -allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding the init method of the Servlet interface Writing Service Method-The service provided by a servlet is implemented in the service method of a GenericServlet, the doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, Trace) of an HttpServlet, Finalizing a Servlet- When a servlet container determines that a servlet should be removed from service it calls the destroy method of the Servlet interface.You release any resources the servlet is using and save any persistent state

The Servlet Interface


All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet A method is also provided that allows a servlet to obtain any initialization parameters.

ServletRequest
The ServletRequest interface is implemented by the server. It enables a servlet to obtain information about a client request. The primary use of ServletRequest is to retrieve the parameters sent by a client.

<form action= > <p> Technology <input type=submit name=tech> </p> <p> State: <select name=state multiple> <option value=mum> Mumbai </option> <option value=del> Delhi </option> <option value=mas> Madras </option> <option value=goa> Goa </option> </select> </p> <input type=submit value=submit> </form>

{
String t=req.getParameter(tech); String city[]=req.getParameterValues(state);

ServletResponse
Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method. To send character data, use the PrintWriter object returned by getWriter() The charset for the MIME body response can be specified with setContentType(java.lang.String)

PrintWriter getWriter()

Returns a PrintWriter object that can send character text to the client Sets the content type of the response being sent to the client. Forces any content in the buffer to be written to the client Returns a boolean indicating if the response has been committed.

void setContentType (String type) void flushBuffer()

boolean isCommitted()

GenericServlet
Defines a generic, protocol-independent servlet The GenericServlet class provides implementations of the basic life cycle methods for a servlet and is typically subclassed by servlet developers. Implements the Servlet and ServletConfig interfaces. GenericServlet makes writing servlets easier a method to append a string to the server log file is available

Import javax.servlet.*; Import java.io.*; public class MyS1 extends GenericServlet { PrintWriter out;RequestDispatcher rd;
public void service(ServletRequest req,ServletResponse res)

{ try { res.setContentType(text/html); rd=req.getRequestDispatcher(/MyS2);

rd.forward(req,res);
}catch(Exception e){} } }

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. TheHttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

javax.servlet.http

Session management
The ability of a protocol to remember the client and its requests is called its state. From this perspective, protocols are divided into two types: stateful and stateless. HTTP is a stateless protocol; each request to a web server and its corresponding response is handled as one isolated transaction. This means that the server cannot maintain the state of the client between multiple requests the server cannot remember the client. A session is an uninterrupted series of requestresponse interactions between a client and a server.

how does a server establish and maintain a session with a client if HTTP does not provide any way to remember the client? There is only one way: When the server receives the first request from a client, the server initiates a session and assigns the session a unique identifier. The client must include this unique identifier with each subsequent request. The server inspects the identifier and associates the request with the corresponding session. This identifier is called a session ID, and the server uses this ID to associate the clients requests in a session.

SESSION SUPPORT
1. A new client sends a request to a server. Since this is the first request, it does not contain any session ID. 2. The server creates a session and assigns it a new session ID. At this time, the session is said to be in the new state The server then sends the ID back to the client with the response. 3. The client gets the session ID and saves it for future requests. This is the first time the client is aware of the existence of a session on the server.

4 The client sends another request, and this time, it sends the session ID with the request. 5 The server receives the request and observes the session ID. It immediately associates the request with the session that it had created earlier. At this time, the client is said to have joined the session, which means the session is no longer in the new state.

Session Tracking
Use four techniques for session management. They operate based on the same principle, although what is passed and how it is passed is different from one to another Hidden Form Field URL Rewriting Cookies HttpSession

Hidden Form Field


Hidden HTML form variables can be used to store state information:
<INPUT TYPE=HIDDEN NAME=session VALUE=972368>

When the form is submitted, the hidden field is sent along with the other input elements' values of the form. On the servlet, the id still can be retrieved using the getParameter method. Hidden variables are not shown to the user by the browser

Advantages 1. simple 2. No effect on security level setting in browsers. Disadvantages 1. size and number of cookies stored are limited. 2. it stored as plain-text in a specific directory, everyone can view and modify them. Personal information is exposed. 3. it won't work if the security level set too high in browser.

Cookies
A cookie is a small piece of information that is passed back and forth in the HTTP request and response. Even though a cookie can be created on the client side using some scripting language such as JavaScript, It is usually created by a server resource, such as a servlet. The cookie sent by a servlet to the client will be passed back to the server when the client requests another page from the same application. Cookies are transferred to and from the client in the HTTP headers.

How to create Cookie ?


In servlet programming, a cookie is represented by the Cookie class in the javax.servlet.http package. You can create a cookie by calling the Cookie class constructor and passing two String objects: the name and value of the cookie. Cookie c1 = new Cookie("myCookie", "secret");

How to send Cookies?


You then can add the cookie to the HTTP response using the addCookie method of the HttpServletResponse interface: response.addCookie(c1); Note that because cookies are carried in the request and response headers, you must not add a cookie after an output has been written to the HttpServletResponse object. Otherwise, an exception will be thrown.

How to retrieve Cookies


To retrieve cookies, you use the getCookies method of the HttpServletRequest interface. This method returns a Cookie array containing all cookies in the request. It is your responsibility to loop through the array to get the cookie you want. Cookie[] cookies = request.getCookies(); int length = cookies.length; for (int i=0; i<length; i++) { Cookie cookie = cookies[i]; out.println("<B>Cookie Name:</B> " + cookie.getName() + "<BR>"); out.println("<B>Cookie Value:</B> " + cookie.getValue() + "<BR>");

How to retrieve Request Headers ?


To display all the headers in the HttpServletRequest method, it first retrieves an Enumeration object containing all the header names. Enumeration enum = request.getHeaderNames(); while (enum.hasMoreElements()) { String header = (String) enum.nextElement(); out.print("<B>" + header + "</B>: "); out.print(request.getHeader(header) + "<BR>"); }

Advantages 1. simple
2. Don't need to send data back to us, browser can participate in this task. 3. unlike URL rewriting, the values of the cookies are not directly visible. 4. you don't need to use any form, which is the requirement of using hidden fields

Disadvantage
1. 2. size and number of cookies stored are limited. it stored as plain-text in a specific directory, everyone can view and modify them. Personal information is exposed. It won't work if the security level set too high in browser. The normal practice is therefore to use cookies with warnings to the user if the application does not work as expected

3.

Persisting Cookies

When the browser is closed, the cookies are deleted. You can choose to persist cookies so that they last longer. The javax.servlet.http.Cookie class has the setMaxAge method that sets the maximum age of the cookie in seconds.

URL Rewriting
In the absence of cookie support, we can attach the session ID to all of the URLs that are within an HTML page that is being sent as a response to the client. That way,when the user clicks on one of the URLs, the session ID is automatically sent back to the server as a part of the request line itself, instead of as a header line. Store the Session ID in the URL: http://www.patkar.edu/session/972368/courses.html Problems: insecure, unreliable, cumbersome, invalidates search engines

Conditions
We should encode all the URLs, including all the hyperlinks and action attributes of the forms, in all the pages of the application. All the pages of the application should be dynamic. Because different users will have different session IDs, there is no way to attach proper session IDs to the URLs present in static HTML pages. All the static HTML pages must be run through a servlet, which would rewrite the URLs while sending the pages to the client. Obviously, this can be a serious performance bottleneck.

Advantages: 1. Every data is appended on the URL => easy to debug. 2. Works even if users disable cookies Disadvantages: 1. URL is lengthy and the length of the URL is limited, can't store much information. 2. The URL contains data. If you send this URL to your friends, they might see your information. 3. If the user surfs to a different site, or to a static section of the same site, the state is lost. 4. insecure, unreliable, cumbersome,

invalidates search engines

HttpSession
The Servlet API abstracts the concept of session through the javax.servlet.http. HttpSession interface. Servlets can use this object to maintain the state of the session. There is an HttpSession object corresponding to each session Session usually use either cookies or URL rewriting Using HttpSession is usually a three-step process: 1 Retrieve the session associated with the request. 2 Add or remove name-value pairs of attributes from the session. 3 Close or invalidate the session if required.

Working with an HttpSession

1 HttpSession session =req.getSession(true);


2 session.setAttribute(count,new Integer(0)); Integer c=(Integer)session.getAttribute(count);

3 session.close()

Advantages:
You can save any set of arbitrary Java objects in a session object. Since the data are stored in server, the size of data is theoretically unlimited.

Disadvantages:
1. HttpSession object internally uses cookies or URL Rewriting for session tracking

Scope of an Attribute
Servlets can share data (objects) using any of three scopes: application (implemented by ServletContext) session (implemented by HttpSession) request (implemented by ServletRequest)

Application Scope
The servlet context is accessible to all the servlets of a web application A servlet can bind an object attribute into the context by name. Any attribute bound into a context is available to any other servlet that is part of the same Web application. Context attributes are LOCAL to the JVM in which they were created. This prevents ServletContext attributes from being a shared memory store in a distributed container

The following methods of ServletContext interface allow access to this functionality: setAttribute -Binds an object to a given attribute name in this servlet context.If the name specified is already used for an attribute, this method will REPLACE the attribute with the new to the new attribute. getAttribute -Returns the servlet container attribute with the given name, or null if there is no attribute by that name. removeAttribute -Removes the attribute with the given name from the servlet context. After removal, subsequent calls to getAttribute(String) to retrieve the attributes value will return null

Session Scope
A servlet can bind an object attribute into an HttpSession implementation by name . Any object bound into a session is available to any other servlet that belongs to the same same ServletContext and handles a request identified as being a part of the same session.

getAttribute -Returns the object bound with the specified name in this session, or null if no object is bound under the name. getAttributeNames -Returns an Enumeration of String objects containing the names of all the objects bound to this session. setAttribute -Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. removeAttribute -Removes the object bound with the specified name from this session.

Request Scope Attributes are objects associated with a request. Attributes may be set by the container to express information that otherwise could not be expressed via the API, or may be set by a servlet to communicate information to another servlet (via the RequestDispatcher). ServletRequest object is used

Attributes are accessed with the following methods of the ServletRequest interface: getAttribute -Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. getAttributeNames -Returns an Enumeration containing the names of the attributes available to this request. setAttribute -Stores an attribute in this request. Attributes are reset between requests. removeAttribute -Removes an attribute from this request.

Servlet Subclass of GenericServlet erv Runs in a server Must be multithreaded or thread safe No direct user interface If downloaded to server, browser, controlled access to files and network network If local to server, full access to files and network

Applet Subclass of Applet Runs in a browser Generally single thread per applet Uses AWT for user interface If downloaded to no access to files and access back only to serving host n/a

JSP Objectives
Introduction - JSP Advantages,Comparing JSP with ASP ,JSP or Servlets? JSP Architecture JSP Access Models JSP Syntax Basics Object Scopes JSP Implicit Objects Synchronization Issues Exception Handling Session Management Standard Actions Using JavaBean Components Forwarding Requests

Request Chaining
Including Requests

JSP Constructs
Comments Hidden output Directives include Page Taglib <%@ include file= <%@ page attr=value %> <%@ taglib uri= %> %> <%-<!-jsp jsp --%> -->

Scripting Element Declaration <%! Expression Scriptlet Action Standard action <jsp:actionname attr=value> Custom action <prefix:tagname attr=value> <%= <%

%> %> %>

Standard Action jsp:useBean jsp:setProperty jsp:getProperty jsp:include jsp:forward jsp:param Jsp:plugin <jsp:useBean attr=value .. /> <jsp:setProperty attr=value .. /> <jsp:getProperty attr=value .. /> <jsp:include attr=value .. /> <jsp:forward attr=value .. /> <jsp:param attr=value .. /> <jsp:plugin attr=value .. />

JSP Directives
JSP directives are messages for the JSP engine. They do not directly produce any visible output, but tell the engine what to do with the rest of the JSP page. Using directive tag, user can import packages, define error handling pages or session information of JSP page. General notation of directive tag is as follows: <%@ tagname attr=value.. %> There are three types of directive tag. 1 Include 2 Page 3 TagLib

Include Directive
The include directive lets you separate your content into more manageable elements, such as those for including a common page header or footer. The page included can be a static HTML page or more JSP content

<%@ include file=fileurl" %>


can be used to include the contents of the indicated file at any location within the JSP page. The included jsp page into the parent jsp page before translating the combined JSP page into single servlet.

Limitation doesnt reload included page. Binds included content to a page at translation time Can lead to incomprehensible JSP.

Page Directive
Page directive provides attribute for the jsp page. Typically, the page directive is found at the top of almost all of your JSP pages. There can be any number of page directives within a JSP page, although the attribute/value pair must be unique <%@ page [ attr=value ]* %>

Attributes language extends Import Session Buffer Autoflush isThreadSafe errorPage isErrorPage contentType Info

Value Java Class name Import list True or false None or size in kb True or false True or false URL for error page True or false Content type info Info about jsp

import- lets you specify a java import declaration.The default [java.lang.*,javax.servlet.*,javax.servlet.http.*] ex. <% page import="java.util.*,java.io.*" %> extends Parent class of the generated servlet.can use to specify the custom parent classes .
<% page extends=myJSp %>

language-specify scripting language used by the jsp.default is java.


Ex <%@ page language=javascript %>

session- Specify whether your jsp participate in an HTTP session.default value is true.if set to false the session object is not available. <% page session=false %> buffer sets the buffer size for the JSPWriter object referenced by the implicit JSP varriable out.default size is 8kb.Buffering capabilities can improve the performance. <%page buffer=12kb %> contentType- sets the MIME type . Default value is text/html. <%@ page contentType=text/html %>

autoFlush: autoFlush attribute is used to specify whether or not to automatically flush out the output buffer when it is full. Syntax of autoFlush attribute available for page directive is written as: <%@ page autoFlush = "true|false" %> In the above example, page and autoFlush are keywords. True or false value can be set to autoFlush attribute, by default, its value is true . This means, the buffer will be flushed automatically when it is full. When the autoflush attribute is set to false, then an exception is thrown when the output buffer gets full and results in overflow.

isThreadSafe: isThreadSafe attribute is used to set whether the generated Servlet handles multiple requests or single requests, depending on the set value of true or false. isThreadSafe attribute is used to set and ensure whether thread safety is implemented in the JSP page. Syntax of isThreadSafe attribute available for page directive is: <%@ page isThreadSafe="true|false" %> In the above statement, page and isThreadSafe are keywords. A true or false value can be set and, by default, the value is set to true. It implies that the JSP container can handle or send multiple concurrent client requests to the JSP page by starting a new thread. If the value of this attribute is set to false, then the JSP container sends client requests only one at a time to the JSP page

info:
Programmers make use of info attribute to place the information or documentation for a page. Details such as: author, version, copyright and date are placed in this attribute. This is actually text string that is written as input text in the compiled JSP page. Syntax of info attribute available for page directive is: <%@ page info = "text" %> In the above statement, page and info are keywords.

errorPage- If the jsp page has no catch block for that exception ,the contaainer automatically forwards the control to a url specify using errorPage attribute. <%@ page errorPage=/my/myerror.jsp %> isErrorPage-Indicates whether you intend that a page be the target of another pages exception.The default value is false. <%@ page isErrorPage=true %>

Standard Actions
Actions allow you to perform sophisticated tasks like instantiating objects and communicating with server-side resources like JSP pages and servlets without requiring Java coding. Although the same can be achieved using Java code within scriptlets, using action tags promotes reusability of your components and enhances the maintainability of your application. Following is the list of JSP standard action elements: 1. jsp:useBean , jsp:setProperty , jsp:getProperty, jsp:params 2. jsp:include,jsp:forward 3. jsp:plugin , jsp:fallback,jsp:params

Using JavaBean Components The component model for JSP technology is based on JavaBeans component architecture. JavaBeans components are nothing but Java objects which follow a well-defined design/naming pattern: the bean encapsulates its properties by declaring them private and provides public accessor (getter/setter) methods for reading and modifying their values

Why to use JavaBean in JSP?


JavaBeans introduces reusability. Component - centric approach, enhances the maintainability of your application. Separation of Responsibility. Avoid Java Code in JSP(Scriptlet)

How to call Java Bean through JSP? Solution to refer -jsp:useBean action element to call set jsp:setProperty to call get- jsp:getProperty

Before you can use a bean in your JSP page, you must make the bean available, using the jsp:useBean action element. The two forms of the jsp:useBean action element are as follows: <jsp:useBean (attribute="value")+/> and <jsp:useBean (attribute="value")+> initialization code </jsp:useBean>

Use Bean Attributes


id -The id attribute defines a unique identifier for the bean. class -The class attribute specifies the fully qualified name for the JavaBean class. type-it specifies the type of the JavaBean class [attribute isn't often used]. scope-the accessibility and the life span of the bean [page,request,session,application]. beanName- represents a name for the bean that the instantiate method of the java.beans.Bean

setProperty
Changing the property of a JavaBean component requires you to use the <jsp:setProperty> tag. For this tag, you identify the bean and property to modify and provide the new value: <jsp:setProperty name="user" property="name" value=abc" /> <jsp:setProperty name="user" property="name" value="<%=expression %>" /> <jsp:setProperty name="user" property="address" param="parameterName" />

<jsp:setProperty name="user" property="*"/>

getProperty
Once you have declared a JavaBean component, you have access to its properties to customize it. The value of a bean's property is accessed using the <jsp:getProperty> tag. With the <jsp:getProperty> tag, you specify the name of the bean to use (from the id field of useBean), as well as the name of the property whose value you are interested in. The actual value is then directly printed to the output: <jsp:getProperty name="user" property="name" />

Forwarding Requests
With the <jsp:forward> tag, you can redirect the request to any JSP, servlet, or static HTML page within the same context as the invoking page. This effectively halts processing of the current page at the point where the redirection occurs, although all processing up to that point still takes place: <jsp:forward page="relativeURL"/> OR <jsp:forward page="relativeURL"> ( <jsp:param . . . /> )* </jsp:include> The invoking page can also pass the target resource bean parameters by placing them into the request,

A <jsp:forward> tag may also have jsp:param subelements that can provide values for some elements in the request used in the forwarding:
<jsp:forward page="<%= somePage %>" > <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" > </jsp:forward>

Including Requests
The <jsp:include> tag can be used to redirect the request to any static or dynamic resource that is in the same context as the calling JSP page. The calling page can also pass the target resource bean parameters by placing them into the request, <jsp:include page="relativeURL" flush="true"/> OR <jsp:include page="relativeURL" flush="true"> ( <jsp:param . . . /> )* </jsp:include>

<jsp:include page="<%= somePage %>" > <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" > </jsp:include>

The included resource, however, cannot set any HTTP headers, which precludes it from doing things like setting cookies, or else an exception is thrown.

Implicit Object
As a convenience feature, the JSP container makes available implicit objects that can be used within scriptlets and expressions, without the page author first having to create them. These objects act as wrappers around underlying Java classes or interfaces typically defined within the Servlet API. request: represents the HttpServletRequest triggering the service invocation. Request scope. response: represents HttpServletResponse to the request. Not used often by page authors. Page scope. pageContext: encapsulates implementation-dependent features in PageContext. Page scope. out: a JspWriter object that writes into the output stream. Page scope.

application: represents the ServletContext obtained from servlet configuration object. Application scope. config: represents the ServletConfig for the JSP. Page scope. page: synonym for the "this" operator, as an HttpJspPage. Not used often by page authors. Page scope. session: An HttpSession. Session scope. exception: the uncaught Throwable object that resulted in the error page being invoked. Page scope.

Object Scopes
The instantiated objects can be associated with a scope attribute defining where there is a reference to the object and when that reference is removed.

Session Management
By default, all JSP pages participate in an HTTP session. The HttpSession object can be accessed within scriptlets through the session implicit JSP object. The session objects is identified by a session ID and stored in the browser as a cookie. If cookies are unsupported by the browser, then the session ID may be maintained by URL rewriting.

To write data setAttribute(String key,Object value) To read data - getAttribute(String key )

architecture of session management

you cannot place primitive data types into the session, you can store any valid Java object There is no limit on the number of objects you can store into the session . invalidate() - Invalidates this session then unbinds any objects bound to it. If the session is invalidated or encounters a session timeout, then the objects within are flagged for garbage collection Session time out can be set setMaxInvalidationInterval(int secs) on the session object <session-config><sesion-timout> in web.xml

JSP Access Models


The early JSP specifications advocated two philosophical approaches, popularly known as Model 1 and Model 2 architectures, for applying JSP technology. These approaches differ essentially in the location at which the bulk of the request processing was performed, and offer a useful paradigm for building applications using JSP technology

Model-1

Advantage Simple Disadvantage may not be desirable for complex implementations. leads to a significant amount of scriptlets or Java code embedded within the JSP page No seperation of presentation and application code. No sharing of responsibility. Multi-Controller-each of the JSP pages must be individually responsible for managing application state and verifying authentication and security.

Model-2

Advantages:
separation of presentation from application code clear delineation of the roles and responsibilities of the developers and page designers Single Controller-making the management of application state, security, and presentation uniform and easier to maintain Disadvantage: Complex

Synchronization
By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state is effectively synchronized . There are two different ways to ensure that the service methods are thread-safe

1 include the JSP page directive <%@ page isThreadSafe="false" %> This causes the JSP page implementation class to implement the SingleThreadModel interface . resulting in the synchronization of the service method, and having multiple instances of the servlet to be loaded in memory. The concurrent client requests are then distributed evenly amongst these instances for processing in a round-robin fashion

Advantages Simple Disadvantages it is not scalable

2 Synchronize block. A better approach is to explicitly synchronize access to shared objects (like those instances with application scope, for example) within the JSP page, using scriptlets: <% synchronized (application) { SharedObject foo = (SharedObject)application.getAttribute("sharedObject"); foo.update(someValue); application.setAttribute("sharedObject",foo);} %>

JavaBean
Objectives: Jar File Introduction to JavaBean Features /Characteristics of JavaBean Introspection Design Pattern [Properties,methods,Events] Bean Info Persistence Customizers Java Bean API

JAR Files
The JAR (Java ARchive) utility provides a convenient way of bundling and deploying Java programs. A JAR file is created by using the jar tool. A JAR file allows you to efficiently deploy a set of classes and their associated resources. JAR technology makes it much easier to deliver and install software. elements in a JAR file are compressed, which makes downloading a JAR file much faster. Digital signatures may also be associated with the individual elements in a JAR file

Content of JAR.
1. A typical JAR file for an application will contain the class files and any other resources needed by the application 2. manifest file is also created and included in the archive.To indicate which of the components in a JAR file are Java Beans / Main Class. Name: slide0.gif Name: slide1.gif Name: slide2.gif Name: slide3.gif Main-Class: Slides Name: slide0.gif Name: slide1.gif Name: slide2.gif Name: slide3.gif Name: Slides.class Java-Bean: True

The JAR Utility


A utility is used to generate a JAR file. Its syntax is shown here:

jar options files

jar cf my.jar *.class *.gif jar cfm my.jar my.mft *.class *.gif

JAR Options
c - A new archive is to be created. C - Change directories during command execution. f - The first element in the file list is the name of the archive that is to be created or accessed. i - Index information should be provided. m - The second element in the file list is the name of the external manifest file. M - Manifest file not created. t - The archive contents should be tabulated. u - Update existing JAR file. v - Verbose output should be provided by the utility as it executes. x - Files are to be extracted from the archive 0 - Do not use compression

Creating a JAR File jar cf Xyz.jar *.class *.gif jar cfm Xyz.jar Yxz.mf *.class *.gif Tabulating the Contents of a JAR File jar tf Xyz.jar Extracting Files from a JAR File jar xf Xyz.jar Updating an Existing JAR File

jar -uf Xyz.jar file1.class Recursing Directories jar -uf Xyz.jar -C directoryX *

JavaBean
A Java Bean is a software component that has been designed to be reusable in a variety of different environments. It enables vendors to create Visual Basic-style environments for developing Java user interfaces with a minimum of programming. There is no restriction on the capability of a Bean. A Bean may be visible or invisible to end user. Bean can execute locally or remotely. Java Bean Objectives Reusability. and interoperability RAD Component-based S.E

Advantages of JavaBean
A Bean obtains all the benefits of Javas write-once, run-anywhere paradigm. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to configure a Bean. The configuration settings of a Bean can be saved in persistent storage and restored at a later time. A Bean may register to receive events from other objects and can generate events that are sent to other objects.

Features /Characteristics of JavaBean Introspection. [ability to present] Persistence. [ability to save] Customizations. [ability to configure]

Introspection
Introspection is the process of analyzing a Bean to determine its capabilities. This is an essential feature of the Java Beans API, because it allows an application builder tool to present information about a component to a software designer. Without introspection, the Java Beans technology could not operate

Introspection means present Info about bean. Whom? Application builder tool What ? Properties ,Methods ,Events How ? Two ways 1 Naming Conventions/Design pattern 2. Addition class- either implement Bean Info interface or extends SimpleBeanInfo class

DesignPattern
Methods N/A Event public void addTListener(TListener eventListener); public void addTListener(TListener eventListener) throws TooManyListeners; public void removeTListener(TListener eventListener);

Properties-set/get

Design Patterns for Properties


A property is a subset of a Beans state. The values assigned to the properties determine the behavior and appearance of that component. Five types of properties. Simple single value. Boolean Two value. Indexed -Multiple value. Bounds Accept the change. Constrained Veto (Reject) the change.

Simple Properties A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property and T is its type.
public T getN( ); public void setN(T arg);

A read/write property has both of these methods to access its values. A read-only property has only a get method. A write-only property has only a set method.

Boolean Properties
A Boolean property has a value of true or false. It can be identified by the following design patterns, where N is the name of the property: public boolean isN( ); public boolean getN( ); public void setN(boolean value); Either the first or second pattern can be used to retrieve the value of a Boolean property. However, if a class has both of these methods, the first pattern is used.

Indexed Property
An indexed property consists of multiple values. It can be identified by the following design patterns, where N is the name of the property and T is its type: public T getN(int index); public void setN(int index, T value); public T[ ] getN( ); public void setN(T values[ ]);

BoundProperty
A bound property gives a JavaBean the capability of notifying another JavaBean when there is a change to the value of that property. The JavaBean that is notified can then react to the change Whenever a bound property changes, notification of the change is sent to interested listeners PropertyChangeEvent PropertyChangeListener PropertyChangeSupport

Constrained Property
Constrained properties are bound properties that go one step further. With a constrained property, an outside object--either a listener Bean or the source Bean itself--can veto a property change .

PropertyChangeEvent VetoableChangeListener VetoableChangeSupport

2. BeanInfo Interface
BeanInfo is used to explicitly control introspection.

SimpleBeanInfo is a class that provides default implementation of the BeanInfo interface. including the three methods.

PropertyDescriptor(String propertyName, Class beanClass)

MethodDescriptor(Method method) EventSetDescriptor(Class sourceClass, String eventSetName, Class listenerType, String listenerMethodName)

Manifest-File
Name: EmployeeInfo.class Name: Employee.class Java-Bean: True

Java Bean API


The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package. Interfaces:

JavaBean Classes

Anda mungkin juga menyukai