Professional Documents
Culture Documents
201
N.V.Ganapathi Raju.
Associate Professor
Contents
JDBC( Java Database Concetivity) SWINGS SERVLETS JSP( Java Server Pages)
Dept., of MCA
GRIET
JDBC PROGRAMS
JDBC driver types JDBC drivers are divided into four types or levels. Each type defines a JDBC driver implementation with increasingly higher levels of platform independence, performance, and deployment administration. The four types are: Type Type Type Type 1: 2: 3: 4: JDBC-ODBC Bridge Native-API/partly Java driver Net-protocol/all-Java driver Native-protocol/all-Java driver
Type 1: JDBC-ODBC Bridge The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many cases, the client database code, must be present on the client machine. Figure 1 shows a typical JDBC-ODBC Bridge environment.
Figure 1. Type 1: JDBC-ODBC Bridge Pros The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Type 1 drivers may be useful for those companies that have an ODBC driver already installed on client machines. Cons The performance is degraded since the JDBC call goes through the bridge to the ODBC driver, then to the native database connectivity interface. The result comes back through the reverse process. Considering the performance issue, type 1 drivers may not be suitable for large-scale applications. The ODBC driver and native connectivity interface must already be installed on the client machine. Thus any advantage of using Java applets in an intranet environment is lost, since the deployment problems of traditional applications remain.
Dept., of MCA
GRIET
Type 2: Native-API/partly Java driver JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine.
Figure 2. Type 2: Native-API/partly Java driver Pros Type 2 drivers typically offer significantly better performance than the JDBC-ODBC Bridge. Cons The vendor database library needs to be loaded on each client machine. Consequently, type 2 drivers cannot be used for the Internet. Type 2 drivers show lower performance than type 3 and type 4 drivers. Type 3: Net-protocol/all-Java driver JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.
Dept., of MCA
GRIET
Figure 3. Type 3: Net-protocol/all-Java driver Pros The net-protocol/all-Java driver is server-based, so there is no need for any vendor database library to be present on client machines. Further, there are many opportunities to optimize portability, performance, and scalability. Moreover, the net protocol can be designed to make the client JDBC driver very small and fast to load. Additionally, a type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. Cons Type 3 drivers require database-specific coding to be done in the middle tier. Additionally, traversing the recordset may take longer, since the data comes through the backend server. Type 4: Native-protocol/all-Java driver The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues.
Dept., of MCA
GRIET
Figure 4. Type 4: Native-protocol/all-Java driver Pros Since type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. Moreover, the native-protocol/all-Java driver boasts better performance than types 1 and 2. Also, there's no need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Cons With type 4 drivers, the user needs a different driver for each database.
Dept., of MCA
GRIET
Dept., of MCA
GRIET
Dept., of MCA
GRIET
// 4.RSMetaDataTest.java
import import public { public { java.sql.*; java.util.*; class RSMetaData static void main(String rags[]) throws Exception
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mydsn","scott", "tiger"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from emp"); ResultSetMetaData meta=rs.getMetaData(); int colCount=meta.getColumnCount(); for(int i=1;i<=colCount;i++) { System.out.print(meta.getColumnName(i)+":"+meta.getColumnType(i)+" | "); } System.out.println(); while(rs.next()) { for(int i=1; i<=colCount; i++) { System.out.print(rs.getString(i)+" | "); } System.out.println(); }// while() rs.close(); stmt.close(); con.close(); }// main() }// class
Dept., of MCA
GRIET
// 5.Database MetadataTest
// TableData.java import java.io.*; import java.sql.*; public class TableData { public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:nvgr"); String x[]={"TABLE"}; DatabaseMetaData dbmd=c.getMetaData(); ResultSet rs=dbmd.getTables(null,null,null,x); while(rs.next()) { System.out.println(rs.getString(3)); } rs.close(); c.close(); } }
Dept., of MCA
GRIET
//6.DatabaseMetadataTest
//ColumnTest.java import java.SQL.*; public class ColumnTest { public static void main(String args[]) throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnetion(jdbc:odbc:mydsn","scott", "tiger"); DatabaseMetaData dbmd=c.getMetaData(); DataInputStream dis=new DataInputStream(System.in); System.out.println(enter table name); String t[]={TABLE} ResultSet rs=dbmd.getColumns(null,null,t,null); While(rs.next()) { System.out.println(Col Name is + rs.getString(4)); System.out.println(Data Type is + rs.getString(6)); System.out.println(Size is + rs.getInt(7)); } rs.close(); c.close(); dis.close(); } }
Dept., of MCA
GRIET
/* 7.Requesting PROCEDURES available in the DB create or replace procedure emp_sal_proc(eno IN number, sal1 OUT number) IS BEGIN SELECT sal INTO sal1 FROM emp WHERE empno=eno; END; / exit */ // ProcExecDemo.java import java.sql.*; public class ProcExecDemo { public static void main(String rags[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger"); CallableStatement cstmt=con.prepareCall("{call emp_sal_proc(?,?)}"); cstmt.setInt(1, Integer.parseInt(rags[0])); cstmt.registerOutParameter(2, Types.DOUBLE); cstmt.execute(); System.out.println(cstmt.getDouble(2)); cstmt.close(); con.close(); }// main() }// class
Dept., of MCA
GRIET
/* 8.Requesting function from JDBC program Function creation: create or replace function emp_sal_func(eno IN number) return number IS sal1 number; BEGIN SELECT sal INTO sal1 FROM emp WHERE empno=eno; return sal1; END; / exit */ // FuncExecDemo.java import java.sql.*; public class FuncExecDemo { public static void main(String rags[]) throws Exception { DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver()); Connection con=DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger"); CallableStatement cstmt=con.prepareCall("{?=call emp_sal_func(?)}"); cstmt.setInt(2, Integer.parseInt(rags[0])); cstmt.registerOutParameter(1, Types.DOUBLE); cstmt.execute(); System.out.println(cstmt.getDouble(1)); cstmt.close(); con.close(); }// main() }// class
Dept., of MCA
GRIET
/* 9.Example on Updatable RS */
// URSDemo.java import java.sql.*; public class URSDemo { public static void main(String rags[]) throws Exception { new oracle.jdbc.driver.OracleDriver(); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@abc:1521:net", "scott", "tiger"); Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs=stmt.executeQuery("SELECT * FROM dept"); rs.absolute(6); //rs.updateString("DNAME", "HumanR"); //rs.updateRow(); rs.deleteRow(); rs.beforeFirst(); while(rs.next()) { System.out.println(rs.getString(2)); }// while() rs.close(); stmt.close(); con.close(); }// main() }// class /* to update a column value in the current row. In a scrollable ResultSet object, the cursor can be moved backwards and forwards, to an absolute position, or to a position relative to the current row. The following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then uses the method updateRow to update the data source table from which rs was derived. rs.absolute(5); rs.updateString("NAME", "AINSWORTH"); rs.updateRow(); */
Dept., of MCA
GRIET
/* 10.Example on Scrollable ResultSet */ // SRSDemo.java import java.sql.*; public class SRSDemo { public static void main(String rags[]) throws Exception { new sun.jdbc.odbc.JdbcOdbcDriver(); Connection con=DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger"); Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=stmt.executeQuery("SELECT * FROM dept"); rs.afterLast(); while(rs.previous()) { System.out.println(rs.getInt(1)+":"+rs.getString(2)+":"+rs.getString(3) ); }// while() Thread.sleep(1000*30); while(rs.next()) { rs.refreshRow(); System.out.println(rs.getInt(1)+":"+rs.getString(2)+":"+rs.getString(3) ); }// while() rs.close(); stmt.close(); con.close(); }// main() }// class /* update dept set dname='HR' where deptno=70; */
Dept., of MCA
GRIET
Dept., of MCA
GRIET
insert into account1 values(1, 10000.00); insert into account1 values(2, 20000.00); commit;*/
SWINGS PROGRAMS
//1. ShowColors.java
// Demonstrating Colors. import java.awt.*; import javax.swing.*; public class ShowColors extends JFrame { // constructor sets window's title bar string and dimensions public ShowColors() { super( "Using colors" ); setSize( 400, 130 ); setVisible( true ); } // draw rectangles and Strings in different colors public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); // set new drawing color using integers g.setColor( new Color( 255, 0, 0 ) ); g.fillRect( 25, 25, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 40 ); // set new drawing color using floats g.setColor( new Color( 0.0f, 1.0f, 0.0f ) ); g.fillRect( 25, 50, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 65 ); // set new drawing color using static Color objects g.setColor( Color.BLUE ); g.fillRect( 25, 75, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 90 ); // display individual RGB values Color color = Color.MAGENTA; g.setColor( color ); g.fillRect( 25, 100, 100, 20 ); g.drawString( "RGB values: " + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue(), 130, 115 ); } // end method paint // execute application
Dept., of MCA
GRIET
public static void main( String args[] ) { ShowColors application = new ShowColors(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class ShowColors
//2. Fonts.java
// Using fonts. import java.awt.*; import javax.swing.*; public class Fonts extends JFrame { // set window's title bar and dimensions public Fonts() { super( "Using fonts" ); setSize( 420, 125 ); setVisible( true ); } // display Strings in different fonts and colors public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); // set font to Serif (Times), bold, 12pt and draw a string g.setFont( new Font( "Serif", Font.BOLD, 12 ) ); g.drawString( "Serif 12 point bold.", 20, 50 ); // set font to Monospaced (Courier), italic, 24pt and draw a string g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) ); g.drawString( "Monospaced 24 point italic.", 20, 70 ); // set font to SansSerif (Helvetica), plain, 14pt and draw a string g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) ); g.drawString( "SansSerif 14 point plain.", 20, 90 ); // set font to Serif (Times), bold/italic, 18pt and draw a string g.setColor( Color.RED ); g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) ); g.drawString( g.getFont().getName() + " " + g.getFont().getSize() + " point bold italic.", 20, 110 ); } // end method paint
Dept., of MCA
GRIET
// execute application public static void main( String args[] ) { Fonts application = new Fonts(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class Fonts
//3.
Metrics.java
// FontMetrics and Graphics methods useful for obtaining font metrics. import java.awt.*; import javax.swing.*; public class Metrics extends JFrame { // set window's title bar String and dimensions public Metrics() { super( "Demonstrating FontMetrics" ); setSize( 510, 210 ); setVisible( true ); } // display font metrics public void paint( Graphics g ) { super.paint( g ); // call superclass's paint method g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) ); FontMetrics metrics = g.getFontMetrics(); g.drawString( "Current font: " + g.getFont(), 10, 40 ); g.drawString( "Ascent: " + metrics.getAscent(), 10, 55 ); g.drawString( "Descent: " + metrics.getDescent(), 10, 70 ); g.drawString( "Height: " + metrics.getHeight(), 10, 85 ); g.drawString( "Leading: " + metrics.getLeading(), 10, 100 ); Font font = new Font( "Serif", Font.ITALIC, 14 ); metrics = g.getFontMetrics( font ); g.setFont( font ); g.drawString( "Current font: " + font, 10, 130 ); g.drawString( "Ascent: " + metrics.getAscent(), 10, 145 ); g.drawString( "Descent: " + metrics.getDescent(), 10, 160 ); g.drawString( "Height: " + metrics.getHeight(), 10, 175 ); g.drawString( "Leading: " + metrics.getLeading(), 10, 190 ); } // end method paint // execute application public static void main( String args[] ) { Metrics application = new Metrics(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
Dept., of MCA
GRIET
// 4 LinesRectsOvals.java
// Drawing lines, rectangles and ovals. import java.awt.*; import javax.swing.*; public class LinesRectsOvals extends JFrame { // set window's title bar String and dimensions public LinesRectsOvals() { super( "Drawing lines, rectangles and ovals" ); setSize( 400, 165 ); setVisible( true ); } // display various lines, rectangles and ovals public void paint( Graphics g ) { super.paint( g ); // call superclass's paint method g.setColor( Color.RED ); g.drawLine( 5, 30, 350, 30 ); g.setColor( Color.BLUE ); g.drawRect( 5, 40, 90, 55 ); g.fillRect( 100, 40, 90, 55 ); g.setColor( Color.CYAN ); g.fillRoundRect( 195, 40, 90, 55, 50, 50 ); g.drawRoundRect( 290, 40, 90, 55, 20, 20 ); g.setColor( Color.YELLOW ); g.draw3DRect( 5, 100, 90, 55, true ); g.fill3DRect( 100, 100, 90, 55, false ); g.setColor( Color.MAGENTA ); g.drawOval( 195, 100, 90, 55 ); g.fillOval( 290, 100, 90, 55 ); } // end method paint // execute application public static void main( String args[] ) { LinesRectsOvals application = new LinesRectsOvals(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class LinesRectsOvals
Dept., of MCA
GRIET
// 5.DrawArcs.java
// Drawing arcs. import java.awt.*; import javax.swing.*; public class DrawArcs extends JFrame { // set window's title bar String and dimensions public DrawArcs() { super( "Drawing Arcs" ); setSize( 300, 170 ); setVisible( true ); } // draw rectangles and arcs public void paint( Graphics g ) { super.paint( g ); // call superclass's paint method // start at 0 and sweep 360 degrees g.setColor( Color.YELLOW ); g.drawRect( 15, 35, 80, 80 ); g.setColor( Color.BLACK ); g.drawArc( 15, 35, 80, 80, 0, 360 ); // start at 0 and sweep 110 degrees g.setColor( Color.YELLOW ); g.drawRect( 100, 35, 80, 80 ); g.setColor( Color.BLACK ); g.drawArc( 100, 35, 80, 80, 0, 110 ); // start at 0 and sweep -270 degrees g.setColor( Color.YELLOW ); g.drawRect( 185, 35, 80, 80 ); g.setColor( Color.BLACK ); g.drawArc( 185, 35, 80, 80, 0, -270 ); // start at 0 and sweep 360 degrees g.fillArc( 15, 120, 80, 40, 0, 360 ); // start at 270 and sweep -90 degrees g.fillArc( 100, 120, 80, 40, 270, -90 ); // start at 0 and sweep -270 degrees g.fillArc( 185, 120, 80, 40, 0, -270 ); } // end method paint // execute application public static void main( String args[] ) { DrawArcs application = new DrawArcs();
Dept., of MCA
GRIET
// 6. DrawPolygons.java
// Drawing polygons. import java.awt.*; import javax.swing.*; public class DrawPolygons extends JFrame { // set window's title bar String and dimensions public DrawPolygons() { super( "Drawing Polygons" ); setSize( 275, 230 ); setVisible( true ); } // draw polygons and polylines public void paint( Graphics g ) { super.paint( g ); // call superclass's paint method int xValues[] = { 20, 40, 50, 30, 20, 15 }; int yValues[] = { 50, 50, 60, 80, 80, 60 }; Polygon polygon1 = new Polygon( xValues, yValues, 6 ); g.drawPolygon( polygon1 ); int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 }; int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 }; g.drawPolyline( xValues2, yValues2, 7 ); int xValues3[] = { 120, 140, 150, 190 }; int yValues3[] = { 40, 70, 80, 60 }; g.fillPolygon( xValues3, yValues3, 4 ); Polygon polygon2 = polygon2.addPoint( polygon2.addPoint( polygon2.addPoint( polygon2.addPoint( polygon2.addPoint( new Polygon(); 165, 135 ); 175, 150 ); 270, 200 ); 200, 220 ); 130, 180 );
g.fillPolygon( polygon2 ); } // end method paint // execute application public static void main( String args[] ) { DrawPolygons application = new DrawPolygons();
Dept., of MCA
GRIET
// 7 LabelTest.java
// Demonstrating the JLabel class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LabelTest extends JFrame { private JLabel label1, label2, label3; // set up GUI public LabelTest() { super( "Testing JLabel" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // JLabel constructor with a string argument label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); container.add( label1 ); // JLabel constructor with string, Icon and alignment arguments Icon bug = new ImageIcon( "bug1.gif" ); label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); label2.setToolTipText( "This is label2" ); container.add( label2 ); // JLabel constructor no arguments label3 = new JLabel(); label3.setText( "Label with icon and text at bottom" ); label3.setIcon( bug ); label3.setHorizontalTextPosition( SwingConstants.CENTER ); label3.setVerticalTextPosition( SwingConstants.BOTTOM ); label3.setToolTipText( "This is label3" ); container.add( label3 ); setSize( 275, 170 ); setVisible( true ); } // end constructor public static void main( String args[] ) { LabelTest application = new LabelTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class LabelTest
Dept., of MCA
GRIET
// 8
ButtonTest.java
// Creating JButtons. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonTest extends JFrame { private JButton plainButton, fancyButton; // set up GUI public ButtonTest() { super( "Testing Buttons" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // create buttons plainButton = new JButton( "Plain Button" ); container.add( plainButton ); Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); container.add( fancyButton ); // create an instance of inner class ButtonHandler // to use for button event handling ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler ); setSize( 275, 100 ); setVisible( true ); } // end ButtonTest constructor public static void main( String args[] ) { ButtonTest application = new ButtonTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // inner class for button event handling private class ButtonHandler implements ActionListener { // handle button event public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( ButtonTest.this, "You pressed: " + event.getActionCommand() );
Dept., of MCA
GRIET
//9 TextFieldTest.java
// Demonstrating the JTextField class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextFieldTest extends JFrame { private JTextField textField1, textField2, textField3; private JPasswordField passwordField; // set up GUI public TextFieldTest() { super( "Testing JTextField and JPasswordField" ); Container container = getContentPane(); container.setLayout( new FlowLayout() ); // construct textfield with default sizing textField1 = new JTextField( 10 ); container.add( textField1 ); // construct textfield with default text textField2 = new JTextField( "Enter text here" ); container.add( textField2 ); // construct textfield with default text, // 20 visible elements and no event handler textField3 = new JTextField( "Uneditable text field", 20 ); textField3.setEditable( false ); container.add( textField3 ); // construct passwordfield with default text passwordField = new JPasswordField( "Hidden text" ); container.add( passwordField ); // register event handlers TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler ); passwordField.addActionListener( handler ); setSize( 325, 100 ); setVisible( true ); } // end constructor TextFieldTest public static void main( String args[] ) { TextFieldTest application = new TextFieldTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
Dept., of MCA
GRIET
// private inner class for event handling private class TextFieldHandler implements ActionListener { // process textfield events public void actionPerformed( ActionEvent event ) { String string = ""; // user pressed Enter in JTextField textField1 if ( event.getSource() == textField1 ) string = "textField1: " + event.getActionCommand(); // user pressed Enter in JTextField textField2 else if ( event.getSource() == textField2 ) string = "textField2: " + event.getActionCommand(); // user pressed Enter in JTextField textField3 else if ( event.getSource() == textField3 ) string = "textField3: " + event.getActionCommand(); // user pressed Enter in JTextField passwordField else if ( event.getSource() == passwordField ) { string = "passwordField: " + new String( passwordField.getPassword() ); } JOptionPane.showMessageDialog( null, string ); } // end method actionPerformed } // end private inner class TextFieldHandler } // end class TextFieldTest
// 10. CheckBoxTest.java
// Creating JCheckBox buttons. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBoxTest extends JFrame { private JTextField field; private JCheckBox bold, italic; // set up GUI public CheckBoxTest() { super( "JCheckBox Test" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() );
Dept., of MCA
GRIET
// set up JTextField and set its font field = new JTextField( "Watch the font style change", 20 ); field.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); container.add( field ); // create checkbox objects bold = new JCheckBox( "Bold" ); container.add( bold ); italic = new JCheckBox( "Italic" ); container.add( italic ); // register listeners for JCheckBoxes CheckBoxHandler handler = new CheckBoxHandler(); bold.addItemListener( handler ); italic.addItemListener( handler ); setSize( 275, 100 ); setVisible( true ); } // end CheckBoxText constructor public static void main( String args[] ) { CheckBoxTest application = new CheckBoxTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // private inner class for ItemListener event handling private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN; // respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold ) valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic ) valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN; // set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } // end method itemStateChanged } // end private inner class CheckBoxHandler } // end class CheckBoxTest
Dept., of MCA
GRIET
// 11: RadioButtonTest.java
// Creating radio buttons using ButtonGroup and JRadioButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButtonTest extends JFrame { private JTextField field; private Font plainFont, boldFont, italicFont, boldItalicFont; private JRadioButton plainButton, boldButton, italicButton, boldItalicButton; private ButtonGroup radioGroup; // create GUI and fonts public RadioButtonTest() { super( "RadioButton Test" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // set up JTextField field = new JTextField( "Watch the font style change", 25 ); container.add( field ); // create radio buttons plainButton = new JRadioButton( "Plain", true ); container.add( plainButton ); boldButton = new JRadioButton( "Bold", false ); container.add( boldButton ); italicButton = new JRadioButton( "Italic", false ); container.add( italicButton ); boldItalicButton = new JRadioButton( "Bold/Italic", false ); container.add( boldItalicButton ); // create logical relationship between JRadioButtons radioGroup = new ButtonGroup(); radioGroup.add( plainButton ); radioGroup.add( boldButton ); radioGroup.add( italicButton ); radioGroup.add( boldItalicButton ); // create font objects plainFont = new Font( "Serif", Font.PLAIN, 14 ); boldFont = new Font( "Serif", Font.BOLD, 14 ); italicFont = new Font( "Serif", Font.ITALIC, 14 ); boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
Dept., of MCA
GRIET
field.setFont( plainFont );
// register events for JRadioButtons plainButton.addItemListener( new RadioButtonHandler( plainFont ) ); boldButton.addItemListener( new RadioButtonHandler( boldFont ) ); italicButton.addItemListener( new RadioButtonHandler( italicFont ) ); boldItalicButton.addItemListener( new RadioButtonHandler( boldItalicFont ) ); setSize( 300, 100 ); setVisible( true ); } // end RadioButtonTest constructor public static void main( String args[] ) { RadioButtonTest application = new RadioButtonTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // private inner class to handle radio button events private class RadioButtonHandler implements ItemListener { private Font font; public RadioButtonHandler( Font f ) { font = f; } // handle radio button events public void itemStateChanged( ItemEvent event ) { field.setFont( font ); } } // end private inner class RadioButtonHandler } // end class RadioButtonTest
// 12. ComboBoxTest.java
// Using a JComboBox to select an image to display. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxTest extends JFrame { private JComboBox imagesComboBox; private JLabel label; private String names[] = { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" }; private Icon icons[] = { new ImageIcon( names[ 0 ] ),
Dept., of MCA
GRIET
new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ), new ImageIcon( names[ 3 ] ) }; // set up GUI public ComboBoxTest() { super( "Testing JComboBox" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // set up JComboBox and register its event handler imagesComboBox = new JComboBox( names ); imagesComboBox.setMaximumRowCount( 3 ); imagesComboBox.addItemListener( new ItemListener() { // anonymous inner class
// handle JComboBox event public void itemStateChanged( ItemEvent event ) { // determine whether check box selected if ( event.getStateChange() == ItemEvent.SELECTED ) label.setIcon( icons[ imagesComboBox.getSelectedIndex() ] ); } } // end anonymous inner class
); // end call to addItemListener container.add( imagesComboBox ); // set up JLabel to display ImageIcons label = new JLabel( icons[ 0 ] ); container.add( label ); setSize( 350, 100 ); setVisible( true ); } // end ComboBoxTest constructor public static void main( String args[] ) { ComboBoxTest application = new ComboBoxTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class ComboBoxTest
Dept., of MCA
GRIET
// 13. ListTest.java
// Selecting colors from a JList. import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class ListTest extends JFrame { private JList colorList; private Container container; private final String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW }; // set up GUI public ListTest() { super( "List Test" ); // get content pane and set its layout container = getContentPane(); container.setLayout( new FlowLayout() ); // create a list with items in colorNames array colorList = new JList( colorNames ); colorList.setVisibleRowCount( 5 ); // do not allow multiple selections colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); // add a JScrollPane containing JList to content pane container.add( new JScrollPane( colorList ) ); colorList.addListSelectionListener( new ListSelectionListener() { // anonymous inner class
// handle list selection events public void valueChanged( ListSelectionEvent event ) { container.setBackground( colors[ colorList.getSelectedIndex() ] ); } } // end anonymous inner class ); // end call to addListSelectionListener
Dept., of MCA
GRIET
setSize( 350, 150 ); setVisible( true ); } // end ListTest constructor public static void main( String args[] ) { ListTest application = new ListTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class ListTest
// 14. BorderLayoutDemo.java
// Demonstrating BorderLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BorderLayoutDemo extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "Hide North", "Hide South", "Hide East", "Hide West", "Hide Center" }; private BorderLayout layout; // set up GUI and event handling public BorderLayoutDemo() { super( "BorderLayout Demo" ); layout = new BorderLayout( 5, 5 ); // 5 pixel gaps // get content pane and set its layout Container container = getContentPane(); container.setLayout( layout ); // instantiate button objects buttons = new JButton[ names.length ]; for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); } // place buttons in BorderLayout; order not important container.add( buttons[ 0 ], BorderLayout.NORTH ); container.add( buttons[ 1 ], BorderLayout.SOUTH ); container.add( buttons[ 2 ], BorderLayout.EAST ); container.add( buttons[ 3 ], BorderLayout.WEST ); container.add( buttons[ 4 ], BorderLayout.CENTER ); setSize( 300, 200 );
Dept., of MCA
GRIET
setVisible( true ); } // end constructor BorderLayoutDemo // handle button events public void actionPerformed( ActionEvent event ) { for ( int count = 0; count < buttons.length; count++ ) if ( event.getSource() == buttons[ count ] ) buttons[ count ].setVisible( false ); else buttons[ count ].setVisible( true ); // re-layout the content pane layout.layoutContainer( getContentPane() ); } public static void main( String args[] ) { BorderLayoutDemo application = new BorderLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class BorderLayoutDemo
// 15: FlowLayoutDemo.java
// Demonstrating FlowLayout alignments. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FlowLayoutDemo extends JFrame { private JButton leftButton, centerButton, rightButton; private Container container; private FlowLayout layout; // set up GUI and register button listeners public FlowLayoutDemo() { super( "FlowLayout Demo" ); layout = new FlowLayout(); // get content pane and set its layout container = getContentPane(); container.setLayout( layout ); // set up leftButton and register listener leftButton = new JButton( "Left" ); container.add( leftButton ); leftButton.addActionListener(
Dept., of MCA
GRIET
new ActionListener() {
// process leftButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.LEFT ); // realign attached components layout.layoutContainer( container ); } } // end anonymous inner class ); // end call to addActionListener
// 16: GridLayoutDemo.java
// Demonstrating GridLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GridLayoutDemo extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "one", "two", "three", "four", "five", "six" }; private boolean toggle = true; private Container container; private GridLayout grid1, grid2; // set up GUI public GridLayoutDemo() { super( "GridLayout Demo" ); // set up layouts grid1 = new GridLayout( 2, 3, 5, 5 ); grid2 = new GridLayout( 3, 2 ); // get content pane and set its layout container = getContentPane(); container.setLayout( grid1 ); // create and add buttons buttons = new JButton[ names.length ]; for ( int count = buttons[ count buttons[ count container.add( } 0; count < names.length; count++ ) { ] = new JButton( names[ count ] ); ].addActionListener( this ); buttons[ count ] );
Dept., of MCA
GRIET
setVisible( true ); } // end constructor GridLayoutDemo // handle button events by toggling between layouts public void actionPerformed( ActionEvent event ) { if ( toggle ) container.setLayout( grid2 ); else container.setLayout( grid1 ); toggle = !toggle; // set toggle to opposite value container.validate(); } public static void main( String args[] ) { GridLayoutDemo application = new GridLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class GridLayoutDemo
//17.JTabbedPaneDemo
import javax.swing.*; /* <applet code="JTabbedPaneDemo" width=400 height=100> </applet> */ public class JTabbedPaneDemo extends JApplet { public void init() { JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities", new CitiesPanel()); jtp.addTab("Colors", new ColorsPanel()); jtp.addTab("Flavors", new FlavorsPanel()); getContentPane().add(jtp); } } class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } }
Dept., of MCA
GRIET
class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"); add(cb1); JCheckBox cb2 = new JCheckBox("Green"); add(cb2); JCheckBox cb3 = new JCheckBox("Blue"); add(cb3); } } class FlavorsPanel extends JPanel { public FlavorsPanel() { JComboBox jcb = new JComboBox(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry"); add(jcb); } }
//18. JScrollPaneDemo
import java.awt.*; import javax.swing.*; /* <applet code="JScrollPaneDemo" width=300 height=250> </applet> */ public class JScrollPaneDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); // Add 400 buttons to a panel JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b; } }
Dept., of MCA
GRIET
// Add panel to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(jp, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER); } }
//19. JTreeEvents
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; /* <applet code="JTreeEvents" width=400 height=200> </applet> */ public class JTreeEvents extends JApplet { JTree tree; JTextField jtf; public void init() { // Get content pane Container contentPane = getContentPane(); // Set layout manager contentPane.setLayout(new BorderLayout()); // Create top node of tree DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); // Create subtree of "A" DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1); DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2); // Create subtree of "B" DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
Dept., of MCA
GRIET
b.add(b3); // Create tree tree = new JTree(top); // Add tree to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(tree, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER); // Add text field to applet jtf = new JTextField("", 20); contentPane.add(jtf, BorderLayout.SOUTH); // Anonymous inner class to handle mouse clicks tree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me); } }); } void doMouseClicked(MouseEvent me) { TreePath tp = tree.getPathForLocation(me.getX(), me.getY()); if(tp != null) jtf.setText(tp.toString()); else jtf.setText(""); } }
//20. JTableDemo
import java.awt.*; import javax.swing.*; /* <applet code="JTableDemo" width=400 height=200> </applet> */ public class JTableDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(); // Set layout manager contentPane.setLayout(new BorderLayout()); // Initialize column headings
Dept., of MCA
GRIET
final String[] colHeads = { "Name", "Phone", "Fax" }; // Initialize data final Object[][] data = { { "Gail", "4567", "8675" }, { "Ken", "7566", "5555" }, { "Viviane", "5634", "5887" }, { "Melanie", "7345", "9222" }, { "Anne", "1237", "3333" }, { "John", "5656", "3144" }, { "Matt", "5672", "2176" }, { "Claire", "6741", "4244" }, { "Erwin", "9023", "5159" }, { "Ellen", "1134", "5332" }, { "Jennifer", "5689", "1212" }, { "Ed", "9030", "1313" }, { "Helen", "6751", "1415" } }; // Create the table JTable table = new JTable(data, colHeads); // Add tree to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER); } }
// read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
Dept., of MCA
GRIET
// read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // TO read number from user as a string
note:- firstNumber = JOptionPane.showInputDialog( "Enter first integer:" ); // add numbers sum = number1 + number2; // display result JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); System.exit( 0 ); } // end method main } // end class Addition // terminate application with window
Dept., of MCA
GRIET
SERVLET PROGRAMS
Dept., of MCA
GRIET
Directory structures of WLAS and Tomcat Web server to store web applications: 1) Tomcat: d:\Tomcat 4.1\webapps\ROOT\ *.html *.jsp .\WEB-INF\ web.xml (configure servlets) .\classes\*.class 2)WLAS: d:\bea\weblogic700\samples\server\stage\examples\examplesWebApp\ *.html *.jsp .\WEB-INF\ web.xml .\classes\ *.class /* 1: HelloServlet.java */ import javax.servlet.*; import java.io.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { ServletOutputStream out=resp.getOutputStream(); out.println("Hello response from Hello Servlet"); out.close(); }// service() }// class classes> javac HelloServlet.java WEB-INF> open web.xml in notepad <web-app> <!---> <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/helloServlet</url-pattern> </servlet-mapping>
Dept., of MCA
GRIET
</web-app> save & exit server startup: d:\Tomcat 4.1\bin\startup.bat request to servlet: http://localhost:8080/helloServlet O/P: Hello response from Hello Servlet deployment into WLAS: 1) copy HelloServlet.class d:\bea\weblogic700\samples\server\stage\examples\examplesWebApp\WEBINF\classes\ 2) update web.xml 3) start server: d:\bea\weblogic700\samples\server\config\examples\startExamplesServer.c md 4) http://localhost:7001/examplesWebApp/helloServlet
// 2 .Http Servlet Example HTML Prg :--------<html> <body> <form action="HttpSer1" method="get"> Name : <input type="text" name="username"/><br> <input type="submit" value="Get Request"/> </form><br> <form action="HttpSer1" method="post"> Name : <input type="text" name="username"/> <br> <input type="submit" value="Post Request"/> </form> </body> </html> import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HttpServletEx1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,java.io.IOException { String value=req.getParameter("username"); res.setContentType("text/html");
Dept., of MCA
GRIET
PrintWriter out=res.getWriter(); out.println("Response from doGet<br>"); out.println("Name : "+value); }//doGet public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,java.io.IOException { String value=req.getParameter("username"); res.setContentType("text/html"); java.io.PrintWriter out=res.getWriter(); out.println("Response from doPost<br>"); out.println("Name : "+value); }//doPost }//class
3.Getting req parameters from HTML ---------------------------------<html> <body> <form action="myapp"> Enter Name : <input type="text" name="username" /> <input type="submit"/> </form> </body> </html> //Servlet Example to show how to get request parameters import javax.servlet.*; import java.io.*; public class RequestParamEx1 extends GenericServlet { public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException { String username=req.getParameter("username"); PrintWriter out=res.getWriter(); out.println("Hello "+username); }//service
Dept., of MCA
GRIET
}//class
4.Requesting all html parameters from html(multiple values also) <HTML> <HEAD> <TITLE>A Sample FORM using GET</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">A Sample FORM using GET</H1> <FORM ACTION="./ShowParamSer"> Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR> Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR> Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR> <HR> First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR> Last Name: <INPUT TYPE="TEXT" NAME="lastName"><BR> Middle Initial: <INPUT TYPE="TEXT" NAME="initial"><BR> Shipping Address: <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR> Credit Card:<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Visa">Visa<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Master Card">Master Card<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Amex">American Express<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Discover">Discover<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Java SmartCard">Java SmartCard<BR> Credit Card Number: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR> Repeat Credit Card Number: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR> <CENTER> <INPUT TYPE="SUBMIT" VALUE="Submit Order"> </CENTER> </FORM> </BODY> </HTML> servlet:--------import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Dept., of MCA
GRIET
response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters"; out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Parameter Name<TH>Parameter Value(s)"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print("<TR><TD>" + paramName + "\n<TD>"); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println("<I>No Value</I>"); else out.println(paramValue); } else { out.println("<UL>"); for(int i=0; i<paramValues.length; i++) { out.println("<LI>" + paramValues[i]); } out.println("</UL>"); } } out.println("</TABLE>\n</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
//Servlet1 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ScopeTestServlet1 extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { //to maintain request level variable req.setAttribute("AttName","Request Scope Valiable");
Dept., of MCA
GRIET
//to maintain session level variables HttpSession hs=req.getSession(); hs.setAttribute("AttName","Session Scope Variable"); //to maintain context level variable ServletContext sc=getServletContext(); sc.setAttribute("AttName","Context Scope Variable"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("In ScopeTestServlet1"); RequestDispatcher rd=req.getRequestDispatcher("/STS2"); rd.include(req,res); out.println("Request Ended"); }//service }//class //Servlet2 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ScopeTestServlet2 extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { HttpSession hs=req.getSession(); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("Response From ScopeServlet2<br>"); String req_v=(String)req.getAttribute("AttName"); if (req_v==null) { out.println("Request Scope Variable not available<br>"); }//if else out.println("Request Variable : "+req_v+"<br>"); String ses_v=(String)hs.getAttribute("AttName"); if (ses_v==null) out.println("Session Scope Variable is Not available"+"<br>"); else out.println("Session Variable : "+ses_v+"<br>"); String con_v=(String)getServletContext().getAttribute("AttName"); if (con_v==null) out.println("Context Scope Variable is not available"+"<br>"); else out.println("Context Scope Variable : "+con_v+"<br>");
Dept., of MCA
GRIET
}//service }//class
Dept., of MCA
GRIET
//AddServlet
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class AddServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String s1=req.getParameter("first"); String s2=req.getParameter("second"); int sum=Integer.parseInt(s1)+Integer.parseInt(s2); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("Sum : "+sum); }//doGet }//class
Dept., of MCA
GRIET
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Servlet1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String s1=req.getParameter("first"); String s2=req.getParameter("second"); try{ Integer.parseInt(s1); Integer.parseInt(s2); }//try catch(NumberFormatException e) { PrintWriter out=res.getWriter(); out.println("In valid numbers"); return; }//catch /* RequestDispatcher rd=getServletContext().getRequestDispatcher("/AddSer"); */ RequestDispatcher rd=getServletContext().getNamedDispatcher("as"); if (rd==null) { PrintWriter out=res.getWriter(); out.println("AddSer not found"); return; }//if //changes res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<b>Message from Servlet1</b><br>"); out.println("First : "+s1+"<br>"); out.println("Second : "+s2+"<br>"); rd.include(req,res); out.println("Response Compleated"); }//doget }//class
//AddServlet
Dept., of MCA
GRIET
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class AddServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String s1=req.getParameter("first"); String s2=req.getParameter("second"); int sum=Integer.parseInt(s1)+Integer.parseInt(s2); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("Sum : "+sum); }//doGet }//class
Dept., of MCA
GRIET
<servlet-class>InitParameterEx</servlet-class> <init-param> <param-name>myparameter</param-name> <param-value>myvalue</param-value> </init-param> </servlet> <servlet> <servlet-name>ip1</servlet-name> <servlet-class>InitParameterEx2 </servlet-class> <init-param> <param-name>param1</param-name> <param-value>value1</param-value> </init-param> <init-param> <param-name>param2</param-name> <param-value>value2</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ip1</servlet-name> <url-pattern>/InitParamEx2</url-pattern> </servlet-mapping>
//InitParameterEx
import javax.servlet.*; import java.io.*; public class InitParameterEx extends GenericServlet { public void init(ServletConfig sc)throws ServletException { super.init(sc); String s=sc.getInitParameter("myparameter"); System.out.println("In init "); System.out.println("myparameter value is "+s); }//init public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException { PrintWriter out=res.getWriter(); out.println("Response from InitParameterEx");
Dept., of MCA
GRIET
//Init Parameter
import javax.servlet.*; import java.io.*; public class InitParameterEx2 extends GenericServlet { public void init() { //this method is called within the init(ServletConfig) method which is implemented in GenericServlet java.util.Enumeration enum=getInitParameterNames(); while(enum.hasMoreElements()) { Object o=enum.nextElement(); String value=getInitParameter((String)o); System.out.println("Name : "+o+" value : "+value); }//while }//init public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException { java.util.Enumeration enum=getInitParameterNames(); res.setContentType("text/html"); PrintWriter out=res.getWriter(); while (enum.hasMoreElements()) { String name=(String)enum.nextElement(); String value=getInitParameter(name); out.println("<b>"+name+"</b>"); out.println("="+value+"<br>"); }//while }//service }//class
Dept., of MCA
GRIET
public class Db extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String s1=req.getParameter("t1"); String s2=req.getParameter("t2"); String s3=req.getParameter("t3"); class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try{ Connection con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"); String q="insert into student values("+s1+",'"+s2+"',"+s3+")"; Statement st=c.createStatement(); int i=st.executeUpdate(q); out.println(i+"record posted"); st.close();c.close(); } catch(Exception e){} } }
11.prg to receive uname,pwd from client and validate in db select the data from the data base
import import import import javax.servlet.*; javax.servlet.http.*; java.sql.*; java.io.*;
Dept., of MCA
GRIET
public class Db1 extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String s1=req.getParameter("uname"); String s2=req.getParameter("pwd"); class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try{ Connection con=DriverManager.getConnection("jdbc:odbc:mydsn","scott","tiger"); String q="select count(*) from logintab whwre user='"+s1+"' and pwd='"+s2"'"; // logintab table contains user , pwd as attributes Statement st=c.createStatement(); ResultSet rs=st.executeQuery(q); rs.next(); int i=rs.getInt(1); if(i>0) out.println("valid user"); else out.println("in valid user");
Dept., of MCA
GRIET
</TR> <TR> <TH>Address</TH> <TD><TEXTAREA name="address">No address</TEXTAREA></TD> </TR> <TR> <TH>Course</TH> <TD>CJ <INPUT type="radio" name="course" value="cj"> AJ <INPUT type="radio" name="course" value="aj"> J2EE <INPUT type="radio" name="course" value="j2ee"></TD> </TR> <TR> <TH>Other courses</TH> <TD><SELECT name="others" MULTIPLE size="5"> <OPTION value="cj">Core Java</OPTION> <OPTION value="aj">Adv Java</OPTION> <OPTION value="j2ee">J2EE</OPTION> </SELECT></TD> </TR> <TR> <TD><INPUT type="submit" name="submit" value="Accept"></TD> </TR> </TABLE> </FORM> </BODY> </HTML> web.xml -------<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>counsellingProcessServlet</servlet-name> <servlet-class>CounsellingProcessServlet</servlet-class> <init-param> <param-name>DRIVER</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </init-param> <init-param> <param-name>URL</param-name> <param-value>jdbc:odbc:mydsn</param-value> </init-param> <init-param> <param-name>USER</param-name> <param-value>scott</param-value> </init-param> <init-param> <param-name>PASS</param-name> <param-value>tiger</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>counsellingProcessServlet</servlet-name>
Dept., of MCA
GRIET
// CounsellingProcessServlet.java
import javax.servlet.*; import java.io.*; import java.sql.*; public class CounsellingProcessServlet extends GenericServlet { PrintWriter out; Connection con; PreparedStatement pstmt; int regId; Statement stmt; ResultSet rs; public { try { String String String String void init(ServletConfig config) throws ServletException
Class.forName(driver); con=DriverManager.getConnection(url, user, pass); stmt=con.createStatement(); pstmt=con.prepareStatement("insert into counselling values(?,?,?,?,?)"); }// try catch(Exception e) { e.printStackTrace(); }// catch() }// init() public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { try { out=resp.getWriter(); String name=req.getParameter("name"); String address=req.getParameter("address"); String course=req.getParameter("course"); String others[]=req.getParameterValues("others"); String other=""; for(int i=0;i<others.length;i++) { other+=others[i]+"&"; } rs=stmt.executeQuery("select max(cid) from counselling");
Dept., of MCA
GRIET
if(rs.next()) { regId=rs.getInt(1); } else { regId=0; } regId++; pstmt.setInt(1, regId); pstmt.setString(2, name); pstmt.setString(3, address); pstmt.setString(4, course); pstmt.setString(5, other); pstmt.executeUpdate(); out.println("Counselling entry successfully accepted RegID is : "+regId); rs.close(); }//try catch(Exception e) { e.printStackTrace(); }// catch() }// service() public void destroy() { try { pstmt.close(); stmt.close(); con.close(); } catch(Exception e){} }// destroy() }// class
Dept., of MCA
GRIET
<TH>User Name</TH> <TD><INPUT type="text" name="user" value=""></TD></TR> <TR><TD><INPUT type="password" name="pass" value=""></TD></TR> <TR><TD><INPUT type="submit" name="submit" value="Login"></TD></TR> </TABLE> </FORM> </BODY> </HTML> <!-LoginFailed.html --> <CENTER><FONT color="red">Login Failed</FONT></CENTER> //LoginValidatorServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import weblogic.servlet.security.*; public class LoginValidatorServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* String user=req.getParameter("user"); String pass=req.getParameter("pass"); */ ServletAuthentication auth=new ServletAuthentication("user", "pass"); int status=auth.weak(req, resp); /* The above function returns AUTHENTICATED if login is successful, returns FAILED_AUTHENTICATION if login fails */ if(status==ServletAuthentication.FAILED_AUTHENTICATION) { resp.sendRedirect("./LoginFailed.html"); } else { RequestDispatcher disp=getServletContext().getNamedDispatcher("viewComposerServlet"); disp.forward(req, resp); }// else }// doPost() }// class
// ViewComposerServlet.java
import import import public { javax.servlet.*; javax.servlet.http.*; java.io.*; class ViewComposerServlet extends HttpServlet
Dept., of MCA
GRIET
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("Login successful"); }// service() }// class web.xml <web-app> <servlet> <servlet-name>loginValidatorServlet</servlet-name> <servlet-class>LoginValidatorServlet</servlet-class> </servlet> <servlet> <servlet-name>viewComposerServlet</servlet-name> <servlet-class>ViewComposerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginValidatorServlet</servlet-name> <url-pattern>/loginValidatorServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>viewComposerServlet</servlet-name> <url-pattern>/viewComposerServlet</url-pattern> </servlet-mapping> </web-app> Compilation: classes> javac *.java component creation: cd.. cd.. jar -cvf dispatcher.war *.* dispatcher> deployment in WLAS: d:\bea\weblogic700\samples\server\config\examples\applications\dispatch er.war start weblogic server: cd.. \examples> startExamplesServer.cmd run: http://localhost:7001/dispatcher/LoginForm.html User: weblogic Pass: weblogic O/P: Login success
Dept., of MCA
GRIET
// ShoppingCartServlet.java
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class ShoppingCartServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // sending MIME type to client resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); HttpSession session=req.getSession(); String submit=req.getParameter("submit"); String prodId=req.getParameter("prodId"); String qty=req.getParameter("qty"); if(submit.equals("Add")) { session.setAttribute(prodId, qty); out.println("Item added to cart"); } else if(submit.equals("Remove")) { session.removeAttribute(prodId); out.println("Item removed from cart"); }
Dept., of MCA
GRIET
else { Enumeration enum=session.getAttributeNames(); out.println("<TABLE border='10'>"); while(enum.hasMoreElements()) { String key=enum.nextElement().toString(); String value=session.getAttribute(key).toString(); out.println("<TR><TD>"+key+"</TD><TD>"+value+"</TD></TR>"); }// while() out.println("</TABLE>"); }// else out.println("Thanks for visiting"); out.close(); }// service() }// class
//CshoppingCartServlet.java
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class CShoppingCartServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out=resp.getWriter();
Dept., of MCA
GRIET
String prodId=req.getParameter("prodId"); String qty=req.getParameter("qty"); String submit=req.getParameter("submit"); if(submit.equals("Add")) { Cookie ck=new Cookie(prodId, qty); resp.addCookie(ck); out.println("Item added"); } else if(submit.equals("Remove")) { Cookie ck=new Cookie(prodId, null); ck.setMaxAge(0); resp.addCookie(ck); out.println("Item deleted"); } else { Cookie ck[]=req.getCookies(); out.println("<TABLE border='10' align='center'>"); for(int i=0;i<ck.length;i++) { out.println("<TR>"); out.println("<TD>"+ck[i].getName()+"</TD>"); out.println("<TD>"+ck[i].getValue()+"</TD>"); out.println("</TR>"); }// for() out.println("</TABLE>"); }// else out.close(); }// service() }// class
Dept., of MCA
GRIET
<servlet> <servlet-name>ls1</servlet-name> <servlet-class>URLRewritingEx1</servlet-class> </servlet> <servlet> <servlet-name>ls2</servlet-name> <servlet-class>URLRewritingEx2</servlet-class> </servlet> <servlet-mapping> <servlet-name>ls1</servlet-name> <url-pattern>/UR1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ls2</servlet-name> <url-pattern>/UR2</url-pattern> </servlet-mapping> </web-app> //URL Rewriting Servlet Program import javax.servlet.*; import java.io.*; public class URLRewritingEx1 extends GenericServlet { public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException { String uname=req.getParameter("uname"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<a href=\"http://localhost:8080/urlrewriting/UR2?uname="+uname+"\"> Next Request </a>"); }//service }//class //URL Rewriting Ex2 import javax.servlet.*; import java.io.*; public class URLRewritingEx2 extends GenericServlet { public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
Dept., of MCA
GRIET
{ String s=req.getParameter("uname"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("User Name : "+s); }//service }//class
Dept., of MCA
GRIET
// HttpSession Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HttpSessionEx1 extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { HttpSession hs=req.getSession(); System.out.println("Session is new "+hs.isNew()); String s=req.getParameter("UserName"); String s1=req.getParameter("pass"); ValidationBean vb=new ValidationBean(); if (vb.validate(s,s1)) { hs.putValue("UserName",s); //or //hs.setAttribute("UserName",s); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<a href=\"http://localhost:8080/session/sessionex2\">"); out.println("Next Request</a>"); }//if }//service }//class //HttpSessionEx2.java package myexamples; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HttpSessionEx2 extends HttpServlet
Dept., of MCA
GRIET
{ public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { HttpSession hs=req.getSession(false); res.setContentType("text/html"); PrintWriter out=res.getWriter(); if (hs==null) { out.println("In Valid Request"); out.println("<br><a href=\"http://localhost:8080/session/sessionex1\">"); out.println("Home</a>"); }//if else { out.println("UserName : "+hs.getValue("UserName")); //or //hs.getAttribute("UserName"); }//else }//service }//class //Validation Bean package myexamples; import java.sql.*; public class ValidationBean { public ValidationBean(){} public boolean validate(String name,String pass) { Connection con=null; Statement st=null; ResultSet rs=null; try{ DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:serve r","scott","tiger");
Dept., of MCA
GRIET
st=con.createStatement(); rs=st.executeQuery("select * from user_tab where name=\'"+name+"\' and pass=\'"+pass+"\'"); if (rs.next()) { return true; }//if }//try catch(SQLException e) {e.printStackTrace();} finally{ try{rs.close();st.close();con.close();} catch(SQLException e) {e.printStackTrace();} }//finally return false; }//validate }//class
Dept., of MCA
GRIET
JSP
Dept., of MCA
GRIET
1.Declarations
Declarations are used to define variables and methods -- both instance and static -- that are likely to be repeated. Thus, they correspond to writing code at the Java Class level. They can also be used to overwrite jspInit or jspDestroy methods that are created when the JSP is compiled. The basic form is: <%! Java variable or method %> Example: <%! String message; %> or <% String message = "Hello, World, from JSP"; %>
2. Expressions
Expressions are references to variables, methods, or composable structures of such. They are most often used as a way of dynamically inserting a value into a parameter slot. You may also think of them as representing a call to a static method. They are evaluated at run time and the results inserted into the output stream at the location of the expression. The basic form is: <%= Java expression %> Example:
Dept., of MCA
GRIET
Scriplets are sections of Java code that are executed in place. They can be as simple as a declaration of a variable that is treated as an instance variable, but they can also include loops that mix Java and HTML. The basic form is: <% Java code %> Example: <% if ( sessionBean.getLoginType() == 0 ) { %> <p align="center"><B>Super User</B></p> <%} else if ( sessionBean.getLoginType() == 1 ) {%> <p align="center"><B>Administrative User</B></p> <%} else if ( sessionBean.getLoginType() == 2 ) {%> <p align="center"><B>Author User</B></p> <%} else {%> <p align="center"><B>Registered User</B></p> <%} %>
Implicit Objects Several local variables are available to scriptlets and expressions through the ServletContext. They include the following:
Dept., of MCA
GRIET
Most are self-explanatory. Application, which is the ServletContext of the JSP and stores attributes for the duration of the application.. Page is the current jsp page and stores attributes associated wit the current page. Out is a writer that can be used by scriptlets to put information onto the output stream.
Directives Directives are instructions to the JSP compiler. The three types of directives are:
Only the include directive will be discussed here. The include directive instructs the JSP compiler to fetch the file referenced in the directive and insert it into the page at that point. Thus, it can be used to include standard boilerplate, such as headers and footers. The basic form is: <%@ directive %> Example: <%@ include file="header.html" %> If the included file is HTML, it should not repeat any HTML HEAD or BODY tags that may already be defined in the output stream. Actions Actions are JSP tags that transfer control to other server objects or perform operations on other objects. They may also generate output. They are another means of building view objects within a M - V - C architecture. There are some half-dozen action tags. The three that will be discussed here are:
include forward useBean
Dept., of MCA
GRIET
All are marked by tags that have the following form: <jsp:action attributes /> Include The include tag is very similar to the include directive, discussed above. It allows content to be included in place. The content may be either static or dynamic. Here is an example: <jsp:include page="header.html" flush="true"/> Forward The forward tag transfer control to a static or dynamic resource, usually referenced by a URL, that exists on the same server. The basic form is: <jsp:forward page="forward_page.html"/> Example: <jsp:forward page="forward_page.html" flush="true"/> UseBean The useBean action is by far the most powerful and the most complex of the JSP actions. It allows a JSP to create an instance or receive an instance of a Java Bean. The JSP could provide typical servlet controller functions by passing the request object to the bean and allowing it to extract user parameters and call back-end functions, just like a servlet. However, supporting those functions in a servlet is generally considered a better practice. However, rather than transferring result values to another type, such as a Hashtable, and passing that object to a JSP, if a back-end process returned a result bean back to a controller servlet, it could simply pass this bean to the relevant JSP. In fact, so long as the Java server supports it and is properly configured, it permits beans to be passed from servlet to JSP, to another JSP, to another servlet, etc. This is called chaining and is an architecture used to provide incrementally processing using filtering principles.
Dept., of MCA
GRIET
JSP Page Scopes All jsp objects exist within a particular scope or context. There are four jsp scopes:
Request and session should be familiar. Page is the current jsp page. Application is the current overall application and can include multiple sessions. Thus, all users sharing a given application, who may be associated with different sessions, would have access to the same set of application-scope resources.
programs
1.HelloWorld.jsp -----------------------<HTML> <HEAD> <TITLE>Hello Program </TITLE> </HEAD> <body> <h1>Hello World message from Ganapathi Raju</h1> <!-- This is JSP comment --> <%out.println("Hello World");%> </body> <html>
2. a.jsp ----------<body> <% @ page language="Java" %> <% out.println("hello world");%> </body> Note: example of Declarations of var:---------------------------------------------<%! int a; %> <%! int a=50; %> <%! int a=50,b=100; %> <%! int a=75;String s="Ganesh"; %> <%! int a=50;float f=10.2f;%>
Dept., of MCA
GRIET
4.decl.jsp -------<HTML> <HEAD> <TITLE>JSP Declarations</TITLE> </HEAD> <BODY> <H1>JSP Declarations</H1> <%! private int accessCount = 0; %> <H2>Accesses to page since server reboot: <%= ++accessCount %></H2> </BODY> </HTML>
5.Loop.jsp ------------<body> <% for (int i=0;i<5;i++){%> <b>Hello</b><br> <%}%> </body> (or) <body> <% for (int i=0;i<5;i++){ out.println("<b>Hello</b><br>"); }%> </body> 6.Expr1.jsp ------------<body> <h1>Data in various sizes</h1> <for(int i=1;i<7;i++){%> <font size=<%=i%>>Hello in size<%=i%> </font> <br> <%}%> </body>
7.Expr2.jsp ----------------<% String c[]={"red","green","blue","yellow"};%> <% for(int i=0;i<c.length;i++){%> <font size=<%=i+1%>Color=<%=c[i]%>>Hello</font> <br> <%}%>
Dept., of MCA
GRIET
// program with page directive 8.Excel.jsp -------<%@ page contentType="application/vnd.ms-excel" %> <%-- Note that there are tabs, not spaces, between columns. --%> 1997 1998 1999 2000 2001 (Anticipated) 12.3 13.4 14.5 15.6 16.7
9.Ex.html ---------<body> here specify the format either "excel" or "html" <form name="f1" action="ApplesAndOranges.jsp"> <br><input type="text" name="format" ><br> <input type="submit"> </body> Ex.jsp ----------<HTML> <HEAD> <TITLE>Comparing Apples and Oranges</TITLE> </HEAD> <BODY> <CENTER> <H2>Comparing Apples and Oranges</H2> <% String format = request.getParameter("format"); if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel"); } %> <TABLE BORDER=1> <TR><TH></TH><TH>Apples<TH>Oranges <TR><TH>First Quarter<TD>2307<TD>4706 <TR><TH>Second Quarter<TD>2982<TD>5104 <TR><TH>Third Quarter<TD>3011<TD>5220 <TR><TH>Fourth Quarter<TD>3055<TD>5287 </TABLE> </CENTER> </BODY> </HTML>
Dept., of MCA
GRIET
//Program with Method Declaration and call 10 met.jsp -----------<body> <%! public int mysum(int a,int b) { return a+b; } %> <%out.println("<h1>sample method invocation</h1>"); int a=mysum(10,20); out.println("data is "+a);%><br><b> <%out.println(" sum is "+mysum(100,300);%> </b> </body>
// HTML TO JSP INTERACTION. 11. page1.html --------<body> <form action="rec.jsp"> Name:-<input type="text" name="t1"><br> <input type="submit" name=b1 value="send"> </form> </body> rec.jsp ----------<body> <h1>JSP TO RECEIVE DATA FROM HTML</h1> <% String s1=request.getParameter("t1";%> <% if(s1.equal("")) response.sendRedirect("error.jsp");%> <b> Data received is <%=s1%>from html</b> </body>
a) JSP PROGRAM to insert data into the data base using method:Html prg:<html> <head> <title> Insert data into the database </title> </head> <body bgcolor="grey" background="a.jpg"> <form name="f1" action="r.jsp">
Dept., of MCA
GRIET
<div align="center"> <h2>Inserting Data into the data base</h2><hr> <table border=0 > <tr><td>No:<input type="text" name="t1"></td> <tr><td>Name:- <input type="text" name="t2"></td> <tr> <td><input type="submit" value="insert"><td></tr> </div> </form> </body> </html>
JSP prg:<body background="a.jpg"> <%@ page language="java" contentType="text/html" %> <%@ page import ="java.sql.*" %> <%! public int insertRec (String a,String b) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mydsn1"); Statement st = c.createStatement(); int i = st.executeUpdate("insert into e values("+a+",'"+b+"')"); st.close(); c.close(); return i; } catch(Exception e) { System.out.println("exception "+e); return 0; } } %> <% String s1 = request.getParameter("t1"); String s2=request.getParameter("t2"); int i = insertRec(s1,s2); out.println(i+"record(s) posted to the database"); %> </body> 12 b) JSP PROGRAM TO SELECT DATA FROM DATABASE HTML PRG:-
Dept., of MCA
GRIET
<html> <head> <title> Read data from data base </title> </head> <body bgcolor="grey" background="a.jpg"> <form name="f2" action="r1.jsp"> <div align="center"> <h2>getting data from database</h2><hr> <table border=0 > <tr> <td><input type="submit" value="select"><td></tr> </div> </form> </body> </html> JSP PRG:<html> <head><title >Table values are</title> </head> <body background="a.jpg"> <%@ page language="java" contentType="text/html" %> <%@ page import ="java.sql.*" %> <h1><center> Tables values are</h1> <hr> <table border="2" cellspacing="10" cellpadding="10"> <tr><th>Eno</th><th>Ename</th></tr> <% { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mydsn1"); Statement st = c.createStatement(); ResultSet rs=st.executeQuery("select eno,ename from e"); while(rs.next()) { System.out.println("1"); %> <tr><td> <%=rs.getString("eno")%></td> <td><%=rs.getString("ename")%><br></td></tr> <% } st.close();
Dept., of MCA
GRIET
<!-CompositeView.jsp
Dept., of MCA
GRIET
--> <%@ include file="Header.html"%> <TR> <TD width="20%"><%@ include file="Menu.html"%></TD> <TD><%@ include file="BodyContent.html"%></TD> </TR> <jsp:include page="Footer.html"/>
JSP Programs with Beans -------------------------------// 14. program shows how to use beans with JSP
//This application combines seperates control layers and presentation layers of MVC.
/* Example on jsp:useBean */
<FORM action="./EmpQuery.jsp"> Empno <INPUT type="text" name="empno" value=""> <INPUT type="submit" name="submit" value="Submit"> </FORM>
<!-EmpQuery.jsp -->
<jsp:useBean id="emp" class="beans.EmpBean"> <jsp:setProperty name="emp" property="empno" value="<%=Integer.parseInt(request.getParameter(\"empno\").trim())%>"/> <jsp:getProperty name="emp" property="ename"/><BR> <jsp:getProperty name="emp" property="job"/><BR> <jsp:getProperty name="emp" property="sal"/><BR> </jsp:useBean>
// EmpBean.java
import java.io.*; public class EmpBean implements Serializable { private int empno; private String ename, job;
Dept., of MCA
GRIET
private double sal; public EmpBean() {} /* public void setEmpno(int empno) { this.empno=empno; } */ public void setEname(String ename) { this.ename=ename; } public void setJob(String job) { this.job=job; } public void setSal(double sal) { this.sal=sal; } public int getEmpno() { return empno; } public String getEname() { return ename; } public String getJob() { return job; } public double getSal() { return sal; } public void setEmpno(int empno) { this.empno=empno; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); java.sql.Connection con=java.sql.DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger"); java.sql.Statement stmt=con.createStatement(); java.sql.ResultSet rs=stmt.executeQuery("select empno, ename, job, sal from emp where empno="+empno);
Dept., of MCA
GRIET
if(rs.next()) { this.ename=rs.getString(2); this.job=rs.getString(3); this.sal=rs.getDouble(4); }// if() rs.close(); stmt.close(); con.close(); }// try catch(Exception e) { e.printStackTrace(); }// catch() }// setEmpno() }// class
<!-15.This application seperates business logic and control layers from presentation layer --> <!-EmpQuery.html -->
<FORM action="./EmpQuery1.jsp"> Empno <INPUT type="text" name="empno" value=""> <INPUT type="submit" name="submit" value="Submit"> </FORM>
<!-EmpQuery1.jsp -->
<jsp:useBean id="emp" class="beans.EmpBean" scope="session"> <jsp:setProperty name="emp" property="empno" value='<%=Integer.parseInt(request.getParameter("empno").trim())%>'/> <jsp:forward page="EmpResult1.jsp"/> </jsp:useBean>
<!-EmpResult1.jsp -->
Dept., of MCA
GRIET
</TR>
// EmpBean.java
import java.io.*; public class EmpBean implements Serializable { private int empno; private String ename, job; private double sal; public EmpBean() {} /* public void setEmpno(int empno) { this.empno=empno; } */ public void setEname(String ename) { this.ename=ename; } public void setJob(String job) { this.job=job; } public void setSal(double sal) { this.sal=sal; } public int getEmpno() { return empno; } public String getEname() { return ename; } public String getJob() { return job; } public double getSal() {
Dept., of MCA
GRIET
return sal; } public void setEmpno(int empno) { this.empno=empno; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); java.sql.Connection con=java.sql.DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger"); java.sql.Statement stmt=con.createStatement(); java.sql.ResultSet rs=stmt.executeQuery("select empno, ename, job, sal from emp where empno="+empno); if(rs.next()) { this.ename=rs.getString(2); this.job=rs.getString(3); this.sal=rs.getDouble(4); }// if() rs.close(); stmt.close(); con.close(); }// try catch(Exception e) { e.printStackTrace(); }// catch() }// setEmpno() }// class
jsp\ EmpQuery.html
Dept., of MCA
GRIET
<FORM action="./empQueryServlet"> Empno <INPUT type="text" name="empno" value=""> <INPUT type="submit" name="submit" value="Submit"> </FORM>
<!-EmpResult.jsp -->
<% beans.EmpBean bean=(beans.EmpBean)session.getAttribute("emp"); %> <TABLE border="20" align="center"> <TR> <TD><%=bean.getEmpno()%></TD> <TD><%=bean.getEname()%></TD> <TD><%=bean.getSal()%></TD> <TD><%=bean.getJob()%></TD> </TR> </TABLE>
// EmpQueryServlet.java
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import beans.*; public class EmpQueryServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int empno=Integer.parseInt(req.getParameter("empno").trim()); EmpBean bean=new EmpBean(); bean.setEmpno(empno); req.getSession().setAttribute("emp", bean); getServletContext().getRequestDispatcher("/EmpResult.jsp").forward(req,resp); }// service() }// class
web.xml ---------
Dept., of MCA
GRIET
<web-app> <servlet> <servlet-name>empQueryServlet</servlet-name> <servlet-class>EmpQueryServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>empQueryServlet</servlet-name> <url-pattern>/empQueryServlet</url-pattern> </servlet-mapping> </web-app>
END
Dept., of MCA
GRIET