Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

May 2, 2018 | Author: cristianlp | Category: Java (Programming Language), Button (Computing), Html Element, Widget (Gui), Typefaces
Share Embed Donate


Short Description

Java manual...

Description

Table of Contents Advanced JAVA Laboratory Manual Unit 1 Introduction Practical 1: Write an applet that draws a circle. The dimension of the applet should be 500 x 300 pixels. The circle should be centered in the applet and have a radius of 100 pixels. Display your name centered in a circle. (USING DRAWOVAL () method) Practical 2: Draw ten red circles in a vertical column in the center of the applet. Practical 3: Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from left to right. Practical 4: Write an applet that displays the position of the mouse at the upper left corner of the applet when it is dragged or moved. Draw a 10x10 pixel rectangle filed with black at the current mouse position. Practical 5: Write an applet that contains one button. Initialize the label on the button to “start”, when the user presses the button change the label between these two values each time the button is pressed. Practical 6: Write an applet that uses the mouse listener, which overrides only two methods which are mouse Pressed and mouseReleased. Exercise: Unit 2 Introduction Practical 7: Write a program that has only one button in the frame, clicking on the button cycles through the colors: red->green->blue->and so on. One color change per click. (use getBackGround() method to get the current color) Practical 8: Write an applet that contains three check boxes and 30 x 30 pixel canvas. The three checkboxes should be labeled “Red”,”Green”,”Blue”. The selection of the check boxes determines the color of the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be purple. Practical 9: Create an application that displays a frame with a menubar. When a user selects any menu or menu item, display that selection on a text area in the center of the frame Practical 10: Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one filled alternately in black and white. Exercise: Unit 3 Introduction Practical 11: Write a database application that uses any JDBC driver. Practical 12: Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update. Practical 13: Write a program to present a set of choice for user to select a product & display the price of product.

Exercise: Unit 4 Introduction Practical 14: Write a simple servlet program which maintains a counter for the number of times it has been accessed since IT’S loading; initialize the counter using deployment descriptor. Practical 15: Create a form processing servlet which demonstrates use of cookies. Practical 16: Create a form processing servlet which demonstrates use of sessions. Unit 5 Introduction Practical 17: WRITE a simple JSP program for user Registration & then control will be transfer it into second page. Practical 18 :Write a simple JSP program for user login form with static & dynamic database. Practical 19 :Write a JSP program to display the grade of a student by accepting the marks of five subjects.



ADVANCED JAVA LABORATORY MANUAL By Gayatri Patel

Advanced JAVA Laboratory Manual Copyright © Reserved by the Author

Advanced JAVA Laboratory Manual Unit 1 Introduction Practical 1: Write an applet that draws a circle. The dimension of the applet should be 500 x 300 pixels. The circle should be centered in the applet and have a radius of 100 pixels. Display your name centered in a circle. (USING DRAWOVAL () method) Practical 2: Draw ten red circles in a vertical column in the center of the applet. Practical 3: Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from left to right. Practical 4: Write an applet that displays the position of the mouse at the upper left corner of the applet when it is dragged or moved. Draw a 10x10 pixel rectangle filed with black at the current mouse position. Practical 5: Write an applet that contains one button. Initialize the label on the button to “start”, when the user presses the button change the label between these two values each time the button is pressed. Practical 6: Write an applet that uses the mouse listener, which overrides only two methods which are mouse Pressed and mouseReleased. Exercise: Unit 2 Introduction Practical 7: Write a program that has only one button in the frame, clicking on the button cycles through the colors: red->green->blue->and so on. One color change per click. (use getBackGround() method to get the current color) Practical 8: Write an applet that contains three check boxes and 30 x 30 pixel canvas. The three checkboxes should be labeled “Red”,”Green”,”Blue”. The selection of the check boxes determines the color of the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be purple. Practical 9: Create an application that displays a frame with a menubar. When a user selects any menu or menu item, display that selection on a text area in the center of the frame Practical 10: Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one filled alternately in black and white. Exercise: Unit 3

Introduction Practical 11: Write a database application that uses any JDBC driver. Practical 12: Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update. Practical 13: Write a program to present a set of choice for user to select a product & display the price of product. Exercise: Unit 4 Introduction Practical 14: Write a simple servlet program which maintains a counter for the number of times it has been accessed since IT’S loading; initialize the counter using deployment descriptor. Practical 15: Create a form processing servlet which demonstrates use of cookies. Practical 16: Create a form processing servlet which demonstrates use of sessions. Unit 5 Introduction Practical 17: WRITE a simple JSP program for user Registration & then control will be transfer it into second page. Practical 18 :Write a simple JSP program for user login form with static & dynamic database. Practical 19 :Write a JSP program to display the grade of a student by accepting the marks of five subjects.

UNIT 1 G ENERAL O BJECTIVES After performing this practical student will be able to: Learn about Applet. Develop an Applet Program in JAVA Execute an Applet Program in JAVA using AppletViewer Execute an Applet in Web Browser Learn How to use Graphics Class to draw Shapes. L EARNING O UTCOMES Explain & Practice Graphic Drawing Applications using Applets. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured.

INTRODUCTION What is an Applet? According to Sun “An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application….The Applet class provides a standard interface between applets and their environment.”

Four definitions of applet: A small application A secure program that runs inside a web browser A subclass of java.applet.Applet An instance of a subclass of java.applet.Applet

The APPLET HTML Tag Applets are embedded in web pages using the and tags. The tag is similar to the tag. The CODE attribute of tag tells the browser where to look for the compiled .class file. It is relative to the location of the source document. The CODEBASE attribute is a URL that points at the directory where the .class

file is. The CODE attribute is the name of the .class file itself. For instance if on the HTML page of the previous section you had written The HEIGHT and WIDTH attributes specify how big a rectangle the browser should set aside for the applet. These numbers are specified in pixels and are required. then the browser would have tried to find TestApplet.class in the classes directory in the same directory as the HTML page that included the applet. On the other hand if you had written then the browser would try to retrieve the applet from http://www.foo.bar.com/classes/ TestApplet.class regardless of where the HTML page was. In short the applet viewer will try to retrieve the applet from the URL given by the formula (CODEBASE + “/” + code). Once this URL is formed all the usual rules about relative and absolute URLs apply. You can leave off the .class extension and just use the class name in the CODE attribute. For example,

Executing Applet using Web Browser TestApplet.java

import java.applet.*; import java.awt.*; public class TestApplet extends Applet { public void paint(Graphics g) { g.drawString(“Welcome to the applet world”,20,40); } } TestApplet.html Applet HTML Page The import statements direct the Java compiler to include the java.applet.Applet and java.awt.Graphics classes in the compilation. The import statement allows these classes to be referenced in the source code using the simple class name (i.e. Applet) instead of the fully qualified class name (i.e. java.applet.Applet). The Applet class provides the framework for the host application to display and control the lifecycle of the applet. The Applet class is an Abstract Windowing Toolkit (AWT) Component, which provides the applet with the capability to display a graphical user interface (GUI) and respond to user events.

Executing Applet directly using Appletviewer TestApplet.java import java.applet.*; import java.awt.*; /* */ public class TestApplet extends Applet

{ public void paint (Graphics g) { g.drawString(“Welcome to Applet world”,20,40); } }

The Basic Applet Life Cycle 1. The browser reads the HTML page and finds any tags. 2. The browser parses the tag to find the CODE and possibly CODEBASE attribute. 3. The browser downloads the .class file for the applet from the URL found in the last step. 4. The browser converts the raw bytes downloaded into a Java class, that is a java.lang.Class object. 5. The browser instantiates the applet class to form an applet object. This requires the applet to have a noargs constructor. 6. The browser calls the applet’s init() method. 7. The browser calls the applet’s start() method. 8. While the applet is running, the browser passes any events intended for the applet, e.g. mouse clicks, key presses, etc., to the applet’s handleEvent() method. Update events are used to tell the applet that it needs to repaint itself. 9. The browser calls the applet’s stop() method. 10. The browser calls the applet’s destroy() method. All applets have the following four methods: public void init(); public void start(); public void stop(); public void destroy();

Simple Methods to Design Applet Method

Description

void setBackground To set the background of an (Color colorname ) applet window. void setForeground To set the foreground color of an (Color colorname ) applet window.

Color getBackground (

To obtain the current settings for the background color

Color getForeground ( )

To obtain the current settings for the foreground color

)

Applet getApplet String name )

(

To obtain the applet specified by given name from the current applet context.

Void showStatus( To display the status message in String status ) the status bar of applet window URL getDocumentBase ( ) URL getCodeBase( )

To obtain the directory of the current browser page. To obtain the directory from which the applet’s class file was loaded

Example: import java.applet.*; import java.awt.*; import java.net.*; /* */ public class AppletMethods extends Applet { String arg; public void start( ) { arg=getParameter(“first”); } public void paint(Graphics g)

{ setBackground(Color.black); setForeground(Color.white); URL codename=getCodeBase( ); URL docname=getDocumentBase( ); g.drawString(“String = Welcome to KDP”,30,40); g.drawString(“Parameter Value = “+arg,30,70); g.drawString(“Class name= “+codename.toString( ),30,100); g.drawString(“DocumentBase = “+docname.toString(),30,130); } } Output:

Passing Parameters to Applets Parameters are passed to applets in NAME=VALUE pairs in tags between the opening and closing APPLET tags. Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class.

Complete syntax for the APPLET tag including Param Tag … alternateHTML Example Applet with parameters /* * AppletWithPara.java * */ import java.applet.*; import java.awt.*; /* */ public class AppletWithPara extends java.applet.Applet { public void paint (Graphics gp) { String au=getParameter(“author”); String ag=getParameter(“age”);

String desg=getParameter(“designation”); String inst=getParameter(“institute”); gp.drawString(“Author:”+au,20,40); gp.drawString(“Age:”+ag,20,70); gp.drawString(“Designation:”+desg,20,100); gp.drawString(“Institute:”+inst,20,130); showStatus(“Parameter methods”); } } Output:

The Coordinate System Java uses the standard, two-dimensional, computer graphics coordinate system. The first visible pixel in the upper left-hand corner of the applet canvas is (0, 0). Coordinates increase to the right and down.

Graphics Objects In Java all drawing takes place via a Graphics object. This is an instance of the class java.awt.Graphics. Initially the Graphics object you use will be the one passed as an argument to an applet’s paint() method. Each Graphics object has its own coordinate system, and all the methods of Graphics including those for drawing Strings, lines, rectangles, circles, polygons and more. Drawing in Java starts with particular Graphics object. You get access to the Graphics object through the paint(Graphics g) method of your applet. Each draw method call will look like g.drawString(“Hello World”, 0, 50) where g is the particular Graphics object with which you’re drawing. Commonly used methods of Graphics class are as follows: drawString ( String s, int x, int y )

To output a string to an applet at a specified position. It is called from within update( ) or paint( ).

drawChars ( char c[ ], int start_index, int To output characters of array to num_of_char, int x, int y ) an applet at specified location. drawChars ( byte c[ ], int start_index, int To output characters of byte’s num_of_char, int x, int y ) array to an applet at specified location. drawLine (int x1, int y1, int x2, int y2);

drawOval ( int x, int y, int width, int

To draw a line at specific location. To draw an oval at specified

height)

location x,y having specific height and width

setColor ( Color c )

To set the color of the object

fillOval ( int x, int y, int width, int height

To fill color in Oval

) drawRect ( int x, int y, int width, int To draw a rectangle at specific height ) location fillRect ( int x, int y, int width, int height

To fill color in rectangle

) drawArc (int x, int y, int width, int height, int arcwidth, int archeight )

To draw an Arc

fillArc (int x, int y, int width, int height, int arcwidth, int archeight )

To fill color in Arc.

setFont ( Font f)

To set the font f

Drawing Lines Drawing straight lines with Java is easy. Just call g.drawLine(x1, y1, x2, y2) where (x1, y1) and (x2, y2) are the endpoints of your lines and g is the Graphics object you’re drawing with. This program draws a line diagonally across the applet. import java.applet.*; import java.awt.*; public class SimpleLine extends Applet { public void paint(Graphics g) { g.drawLine(0, 0, this.getSize().width, this.getSize().height);

} } Output

Drawing Rectangles Drawing rectangles is simple. Start with a Graphics object g and call its drawRect() method: public void drawRect(int x, int y, int width, int height) As the variable names suggest, the first int is the left hand side of the rectangle, the second is the top of the rectangle, the third is the width and the fourth is the height. This is in contrast to some APIs where the four sides of the rectangle are given. This uses drawRect() to draw a rectangle around the sides of an applet.

import java.applet.*; import java.awt.*; public class RectangleApplet extends Applet { public void paint(Graphics g) { g.drawRect(0, 0, this.getSize().width - 1, this.getSize().height - 1); } } Output Remember that getSize().width is the width of the applet and getSize().height is its height. Why was the rectangle drawn only to getSize().height-1 and getSize().width-1? Remember that the upper left hand corner of the applet starts at (0, 0), not at (1, 1). This means that a 100 by 200 pixel applet includes the points with x coordinates between 0 and 99, not between 0 and 100. Similarly the y coordinates are between 0 and 199 inclusive, not 0 and 200.

Filling Rectangles The drawRect() method draws an open rectangle, a box if you prefer. If you want to draw a filled rectangle, use the fillRect() method. Otherwise the syntax is identical. This program draws a filled square in the center of the applet. This requires you to separate the applet width and height from the rectangle width and height. Here’s the code: import java.applet.*; import java.awt.*;

public class FillAndCenter extends Applet { public void paint(Graphics g) { int appletHeight = this.getSize().height; int appletWidth = this.getSize().width; int rectHeight = appletHeight/3; int rectWidth = appletWidth/3; int rectTop = (appletHeight - rectHeight)/2; int rectLeft = (appletWidth - rectWidth)/2; g.fillRect(rectLeft, rectTop, rectWidth-1, rectHeight-1); } } Output

Ovals and Circles Java has methods to draw outlined and filled ovals. As you’d probably guess these methods are called drawOval() and fillOval() respectively. As you might not guess they take identical arguments to drawRect() and fillRect(), i.e. public void drawOval(int left, int top, int width, int height) public void fillOval(int left, int top, int width, int height) Instead of the dimensions of the oval itself, the dimensions of the smallest rectangle which can enclose the oval are specified. The oval is drawn as large as it can be to touch the rectangle’s edges at their centers. This picture may help:

The arguments to drawOval() are the same as the arguments to drawRect(). The first int is the left hand side of the enclosing rectangle, the second is the top of the enclosing rectangle, the third is the width and the fourth is the height. Example: import java.applet.*; import java.awt.*; public class Bullseye extends Applet { public void paint(Graphics g) { int appletHeight = this.getSize().height; int appletWidth = this.getSize().width; for (int i=8; i >= 0; i—) { if ((i % 2) == 0) g.setColor(Color.red); else g.setColor(Color.white);

// Center the rectangle int rectHeight = appletHeight*i/8; int rectWidth = appletWidth*i/8; int rectLeft = appletWidth/2 - i*appletWidth/16; int rectTop = appletHeight/2 - i*appletHeight/16; g.fillOval(rectLeft, rectTop, rectWidth, rectHeight); } } } Output

Using Colors with Applets The syntax of the constructor to create custom colors: Color ( int red, int green, int blue); Example: new Color (255, 100, 100); // light red Calling a constructor to set the color Color c=new Color (255, 175, 175) g.setColor (c) Color Obtained

Red Value

Green Value

Blue Value

White

255

255

255

Black

0

0

0

Light Gray

192

192

192

Dark Gray

128

128

128

Red

255

0

0

Green

0

255

0

Blue

0

0

255

Yellow

255

255

0

Purple

255

0

255

Table of RGB values of common colors You create new colors using the same RGB triples that you use to set background colors on web pages. However you use decimal numbers instead of the hex values used by the bgcolor tag. For example medium gray is Color(127, 127, 127). Pure white is Color(255, 255, 255). Pure red is (255, 0, 0) and so on. As with any variable you should give your colors descriptive names. For instance Color medGray = new Color(127, 127, 127);

Color cream = new Color(255, 231, 187); Color lightGreen = new Color(0, 55, 0); A few of the most common colors are available by name. These are Color.black

Color.gray

Color.orange

Color.yellow

Color.blue

Color.green

Color.pink



Color.cyan

Color.lightGray

Color.red



Color.darkGray

Color.magenta

Color.white



To change colors you change the color of your Graphics object. Then everything you draw from that point forward will be in the new color until you change it again. When an applet starts running the color is set to black by default. You can change this to red by calling g.setColor(Color.red). You can change it back to black by calling g.setColor(Color.black). The following code fragment shows how you’d draw a pink String followed by a green one: g.setColor(Color.pink); g.drawString(“This String is pink!”, 50, 25); g.setColor(Color.green); g.drawString(“This String is green!”, 50, 50); Example: AppletColor.java import java.applet.*; import java.awt.*; /* */ public class AppletColor extends Applet { public void paint(Graphics g) { Color c1=new Color(255,0,255);

Color c2=new Color(128,128,128); g.setColor(c1); int r=c1.getRed( ); int gr=c1.getGreen( ); int b=c1.getBlue( ); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,20); c1=c1.darker( ); g.setColor(c1); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,40); g.setColor(c2); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,60); c2=c2.brighter( ); g.setColor(c2); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,80); } } Output:

Fonts You’ve already seen one example of drawing text in the HelloWorldApplet program of

the last chapter. You call the drawString() method of the Graphics object. This method is passed the String you want to draw as well as an x and y coordinate. If g is a Graphics object, then the syntax is g.drawString(String s, int x, int y) The String is simply the text you want to draw. The two integers are the x and y coordinates of the lower left-hand corner of the String. The String will be drawn above and to the right of this point. However letters with descenders like y and p may have their descenders drawn below the line. Until now all the applets have used the default font, probably some variation of Helvetica though this is platform dependent. However unlike HTML Java does allow you to choose your fonts. Java implementations are guaranteed to have a serif font like Times that can be accessed with the name “Serif”, a monospaced font like courier that can be accessed with the name “Mono”, and a sans serif font like Helvetica that can be accessed with the name “SansSerif”. The following applet lists the fonts available on the system it’s running on. It does this by using the getFontList() method from java.awt.Toolkit. This method returns an array of strings containing the names of the available fonts. These may or may not be the same as the fonts installed on your system. It’s implementation dependent whether or not all the fonts a system has are available to the applet. import java.awt.*; import java.applet.*; public class FontList extends Applet { private String[] availableFonts; public void init () { Toolkit t = Toolkit.getDefaultToolkit(); availableFonts = t.getFontList(); } public void paint(Graphics g) { for (int i = 0; i < availableFonts.length; i++) {

g.drawString(availableFonts[i], 5, 15*(i+1)); } } } Output

Drawing Graphics Example: GraphicsDemo.java import java.awt.*; import java.applet.*; /* */ public class GraphicsDemo extends Applet { public void paint(Graphics g) { setBackground(Color.pink); setForeground(Color.blue); Font f=new Font(“Arial”,Font.ITALIC,10);

g.setFont(f); g.drawLine(20,20,50,50); g.drawString(“Line”,20,70); g.drawRect(100,20,50,50); g.drawString(“Rectangle”,100,100); g.fillRoundRect(200,20,80,50,10,10); g.drawString(“Filled Round Rect”,200,100); g.drawOval(20,100,50,80); g.drawString(“Oval”,25,200); g.fillOval(100,130,50,50); g.drawString(“Circle”,110,200); g.drawString(“WELCOME TO GRAPHICS”,130,350); } } Output:

PRACTICAL 1: WRITE AN APPLET THAT DRAWS A CIRCLE. THE DIMENSION OF THE APPLET SHOULD BE 500 X 300 PIXELS. THE CIRCLE SHOULD BE CENTERED IN THE APPLET AND HAVE A RADIUS OF 100 PIXELS. DISPLAY YOUR NAME CENTERED IN A CIRCLE. (USING DRAWOVAL () METHOD) S PECIFIC O BJECTIVES

After performing this practical student will be able to: Learn about Applet. Develop an Applet Program in JAVA Execute an Applet Program in JAVA using AppletViewer Execute an Applet in Web Browser Learn How to use Graphics Class to draw Circle. L EARNING O UTCOMES Explain & Practice Graphic Drawing method drawOval() to draw circle. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development E NVIRONMENT VARIABLES LIKE JAVA_H OME , P ATH , C LASSPATH ARE CONFIGURED .C ODE import java.awt.*; import java.applet.*; /* */ public class CenterCircle extends Applet { int w,h; public void init() { w=getWidth(); h=getHeight(); } public void paint(Graphics g) { g.setColor (Color.blue); g.drawOval ((w/2)-50,(h/2)-50,100,100); g.drawString(“J.B.Patel”, w/2,h/2);

g.setColor (Color.green); showStatus (“This applet draws circle in the center of the applet”); } } O UTPUT

PRACTICAL 2: DRAW TEN RED CIRCLES IN A VERTICAL COLUMN IN THE CENTER OF THE APPLET. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop an Applet Program in JAVA Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to use Graphics Class to draw Circle. L EARNING O UTCOMES Explain & Practice Graphic Drawing method drawOval () to draw circles pattern and setColor() to fill Circle. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. C ODE import java.awt.*; import java.applet.*; /* */ public class TenRed extends Applet { int w,h; public void init()

{ w=getWidth(); h=getHeight(); } public void paint(Graphics g) { int count=0; g.setColor (Color.red); for(int i=h;i>0;i=i-50) { g.fillOval(w/2-25,h-i,50,50); count++; if (count==10) break; } } } O UTPUT

PRACTICAL 3: BUILT AN APPLET THAT DISPLAYS A HORIZONTAL RECTANGLE IN ITS CENTER. LET THE RECTANGLE FILL WITH COLOR FROM LEFT TO RIGHT. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop an Applet Program in JAVA Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to use Graphics Class to draw and fill Rectangles. L EARNING O UTCOMES Explain & Practice Graphic Drawing method drawRect() and fillRect() to create Progress bar. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development

Environment variables like JAVA_Home, Path, Classpath are configured. C ODE import java.awt.*; import java.applet.*; /* */ public class FillRectGrad extends Applet { int w,h, x1=100,x2,y1=50,y2=150, flag=0; Thread t; Graphics g1; public void init() { w=getWidth(); h=getHeight(); } public void paint(Graphics g) { g.setColor(java.awt.Color.red); g.drawRect(100,50,300,150); for(x2=100;x2BLUE->AND SO ON. ONE COLOR CHANGE PER CLICK. (USE GETBACKGROUND() METHOD TO GET THE CURRENT COLOR) S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop an AWT Program in JAVA using Button Control Learn How to handle Button Events using ActionListener interfaces. L EARNING O UTCOMES Explain & Practice Button Events. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. C ODE import java.awt.*;

import java.applet.*; import java.awt.event.*; import java.lang.String; class ChangeColor extends Applet implements ActionListener { Button b1; public void init() { b1=new Button(“Change Color”); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { String s; s=b1.getBackground(); if(s==“Change Color”) { this.setBackground(Color.RED); b1.setLabel(“Green”); } if(s==“Green”) { this.setBackground(Color.GREEN); b1.setLabel(“Blue”); } if(s==“Blue”) { this.setBackground(Color.BLUE); b1.setLabel(“Change Color”);

} } } } public class ColorPickerDemo extends Frame { public static void main(String [] args) { Frame f = new Frame(“Color Picker Demo”); ChangeColor c = new ChangeColor(); c.init(); f.add(“Center”, c); f.pack(); f.show(); } } O UTPUT :

PRACTICAL 8: WRITE AN APPLET THAT CONTAINS THREE CHECK BOXES AND 30 X 30 PIXEL CANVAS. THE THREE CHECKBOXES SHOULD BE LABELED “RED”,”GREEN”,”BLUE”. THE SELECTION OF THE CHECK BOXES DETERMINES THE COLOR OF THE CANVAS. FOR EXAMPLE, IF THE USER SELECTS BOTH “RED” AND “BLUE”, THE CANVAS SHOULD BE PURPLE. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop an AWT Program in JAVA using Checkbox and Canvas Control

Learn How to handle Checkbox Events using ItemListener interfaces. L EARNING O UTCOMES Explain & Practice Checkbox Events. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. C ODE : import java.awt.*; import java.applet.*; import java.awt.event.*; import java.lang.String; public class CanvasColorDemo extends Applet implements ItemListener { Checkbox ch1,ch2,ch3; int c1,c2,c3; //c1=c2=c3=0; Canvas c=new Canvas(); public void init() { setLayout(new GridLayout(1,4)); //ColorGroup=new CheckboxGroup(); ch1=new Checkbox(“RED”,false); ch2=new Checkbox(“GREEN”,false); ch3=new Checkbox(“BLUE”,false); add(ch1); add(ch2); add(ch3); ch1.addItemListener(this);

ch2.addItemListener(this); ch3.addItemListener(this); c.setBackground(Color.CYAN); c.setVisible(true); add(c); } public void itemStateChanged(ItemEvent e) { if(e.getSource()==ch1) if(c1!=255) c1=255; else c1=0; if(e.getSource()==ch2) if(c2!=255) c2=255; else c2=0; if(e.getSource()==ch3) if(c3!=255) c3=255; else c3=0; c.setBackground(new Color(c1,c2,c3)); repaint(); } } O UTPUT :



PRACTICAL 9: CREATE AN APPLICATION THAT DISPLAYS A FRAME WITH A MENUBAR. WHEN A USER SELECTS ANY MENU OR MENU ITEM, DISPLAY THAT SELECTION ON A TEXT AREA IN THE CENTER OF THE FRAME

S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop an AWT Program in JAVA using Menu and TextArea Learn How to handle Menu Events using ActionListener interfaces. L EARNING O UTCOMES Explain & Practice Menu Events. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. C ODE : /*MenuDemo.java*/ import java.awt.*; import java.awt.event.*; import java.applet.*; public class MenuDemo extends Applet implements ActionListener { private TextField myTextField; private Frame myFrame;

public void init() { myFrame = new Frame(); myFrame.addWindowListener(new Terminator()); myTextField = new TextField(20); add(myTextField); myFrame.setBounds(200,200,300,300); // place myMenuBar at top of myFrame MenuBar myMenuBar = new MenuBar(); myFrame.setMenuBar(myMenuBar); Menu fileMenu = new Menu(“File”); myMenuBar.add(fileMenu); Menu editMenu = new Menu(“Edit”); myMenuBar.add(editMenu); MenuItem myMenuItem; myMenuItem = new MenuItem(“Open”); myMenuItem.addActionListener(this); fileMenu.add(myMenuItem); myMenuItem = new MenuItem(“Close”); myMenuItem.addActionListener(this); fileMenu.add(myMenuItem); myMenuItem = new MenuItem(“Undo”); myMenuItem.addActionListener(this); editMenu.add(myMenuItem);

myFrame.show(); } public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof MenuItem) myTextField.setText(“Your Choice: ” + e.getActionCommand()); } public class Terminator extends WindowAdapter { public void windowClosing(WindowEvent e) { myFrame.dispose(); // use System.exit(0) for applications } } } O UTPUT :

PRACTICAL 10: WRITE AN APPLET THAT DRAWS TWO SETS OF EVERDECREASING RECTANGLES ONE IN OUTLINE FORM AND ONE FILLED ALTERNATELY IN BLACK AND WHITE.

S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop an AWT Program in JAVA using Graphics Class Methods like drawRect() and fillRect() L EARNING O UTCOMES Explain & Practice Graphics Class Methods. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. C ODE : import java.awt.*; import java.awt.event.*; import java.applet.*; public class RectApplet extends Applet { public static final int W = 200; public static final int H = 200; public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.WHITE); for (int x = 0; x < getWidth() / 2; x += 5) { int x1 = (getWidth() / 2) - x; int y1 = (getHeight() / 2) - x;

g.drawRect(x1, y1, x * 2, x * 2); } } public static void main(String args[]) { Applet applet = new RectApplet(); Frame frame = new Frame(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.add(applet); frame.setSize(W, H); frame.show(); } } O UTPUT :

EXERCISE:

D EVELOP AN APPLET TO DISPLAY THE MESSAGE “H APPY N EW Y EAR ” WITHIN A TEXT FIELD . Code:

Output: E XTEND THE PREVIOUS PROGRAM SO THAT THE MESSAGE “H APPY N EW Y EAR ” WILL APPEAR WITHIN A TEXT FIELD WHEN THE BUTTON WITH THE CAPTION “Y EAR ” IS PUSHED , WHILE THE MESSAGE “H APPY N EW M ILLENIUM ” WILL APPEAR WITHIN THE TEXT FIELD WHEN THE BUTTON WITH THE CAPTION “ MILLENIUM ” IS PUSHED . Code:

Output: B UILD AN APPLET THAT RECEIVES THE RADIUS OF A CIRCLE THROUGH A TEXT FIELD AND COMPUTES THE AREA WHEN THE BUTTON “A REA ” IS PUSHED . T HE AREA SHOULD APPEAR IN A SEPERATE TEXT FIELD . THE FIRST TEXT FIELD SHOULD BE PRECEEDED BY THE LABEL “E NTER

THE R ADIUS ”, WHILE THE SECOND TEXT FIELD SHOULD BE PRECEEDED BY THE LABEL “A REA IS EQUAL TO ”.

Code:

Output: C REATE TWO CHECKBOXES WITH THE CAPTION “COM” AND “COBRA”. C REATE TWO TEXT FIELDS . U SE THE FIRST TO INDICATE THE STATUS OF THE FIRST CHECKBOX AND THE SECOND TEXT FIELD TO INDICATE THE STATUS OF THE SECOND CHECKBOX . Code:

Output:

W RITE AN APPLET TO DISPLAY FOUR RADIO BUTTONS WITH THE CAPTIONS “S ANDWICH 1”, “S ANDWICH 2”, “S ANDWICH 3” AND “S ANDWICH 4”. C REATE A TEXT FIELD AND USE IT TO INDICATE WHICH DISH IS SELECTED . Code:

Output: C REATE A CHOICE CONTROL TO SELECT ONE OF THE FOUR FONTS “T IMES ”, “S ARIF ”, “S AN S ARIF ” AND “R OMAN ”. C REATE ANOTHER CHOICE CONTROL TO SELECT ON OF THE FIVE COLOURS GREEN , RED , YELLOW , WHITE AND ORANGE . M AKE PROVISION TO REPORT THE SELECTED COLOUR IN THE FORM OF A LABEL . Code:

Output: A MENU BAR CONTAINS 3 MENUS NAMED S ALES F ILE 1, S ALES F ILE 2, AND S ALES F ILE 3. E ACH ONE OF THESE 3 MENUS HAS THE 3 OPTIONS NAMED CREATE , UPDATE AND PRINT . W RITE AN APPLET FOR CREATING AND DISPLAYING ALL THE 3 MENUS WITH THEIR OPTIONS . Code:



Output:

UNIT 3 G ENERAL O BJECTIVES After performing this practical student will be able to: Learn how to use JDBC to connect database. Develop and execute a JDBC application to create/read/update/delete records into database. Learn how to use JDBC API and JDBC Drivers for databae functions. L EARNING O UTCOMES Explain JDBC concepts and Practice JDBC programs. A SSUMPTIONS Oracle JDK installed, MySQL Java Connector installed and configured. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured.

INTRODUCTION JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage: Making a connection to a database Creating SQL or MySQL statements Executing that SQL or MySQL queries in the database Viewing & Modifying the resulting records The basic steps to get your program up and running are: Load the driver and register it with the driver manager Connect to a database Create a statement Execute a query and retrieve the results, or make changes to the database Disconnect from the database Steps 1 and 2 are the only DBMS-specific steps. Here is the code that loads the driver and registers it with the JDBC driver manager: DriverManager.registerDriver(new com.mysql.jdbc.Driver ()); Here is another way of doing the above:

Class.forName(“com.mysql.jdbc.Driver”); Following are driver string for some of the popular databases, MySQL JDBC Connection URL: jdbc:mysql://hostname:3306/ – 3306 is mysql default port Java DB Connection URL: jdbc:derby:testdb;create=true Microsoft SQL Server JDBC Connection URL: jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=northwind Oracle JDBC connection URL: jdbc:oracle:thin:@hostname:1521:MyDatabase

Connecting to a Database The DriverManager class provides the static getConnection() method for opening a database connection. Below is the method description for getConnection(): public static Connection getConnection(String url, String userid, String password) throws SQLException

Getting connection Connection connection = DriverManager.getConnection(“jdbc:jdbcDriver:database”, username, password);

Query execution and getting result Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(“SELECT * FROM table”);

Parsing the result from ResultSet while (resultSet.next()) { int field1= rs.getInt(“field1”); String field2= rs.getString(“field2”); }

PRACTICAL 11: WRITE A DATABASE APPLICATION THAT USES ANY JDBC DRIVER. S PECIFIC O BJECTIVES After performing this practical student will be able to: Learn how to use JDBC to connect to database.

Learn how to use JDBC API and JDBC Drivers for databae functions. L EARNING O UTCOMES Explain JDBC concepts and Practice JDBC programs to connect to MySQL Database. A SSUMPTIONS Oracle JDK installed, MySQL Java Connector installed and configured. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, path, classpath are configured. C ODE //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = “com.mysql.jdbc.Driver”; static final String DB_URL = “jdbc:mysql://localhost/”; // Database credentials static final String USER = “root”; static final String PASS = ””; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName(“com.mysql.jdbc.Driver”); //STEP 3: Open a connection System.out.println(“Connecting to database…”); conn = DriverManager.getConnection(DB_URL, “USER”, “PASS” ); //STEP 4: Execute a query System.out.println(“Creating database…”);

stmt = conn.createStatement(); String sql = “CREATE DATABASE STUDENTS”; stmt.executeUpdate(sql); System.out.println(“Database created successfully…”); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println(“Goodbye!”); }//end main }//end JDBCExample O UTPUT : Connecting to database… Creating database…

Database created successfully… Goodbye! Process completed.

PRACTICAL 12: DEVELOP A UI THAT PERFORMS THE FOLLOWING SQL OPERATIONS:1) INSERT 2)DELETE 3)UPDATE. S PECIFIC O BJECTIVES After performing this practical student will be able to: Learn how to use JDBC to perform CRUD Operation (Create/ Read/ Update/ Delete) Learn how to use JDBC API and JDBC Drivers for databae functions. L EARNING O UTCOMES Explain JDBC concepts and Practice database operations using JDBC. A SSUMPTIONS Oracle JDK installed, MySQL Java Connector installed and configured. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, path, classpath are configured. C ODE import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame;

import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class JDBCCRUD implements ActionListener { JLabel lblFname,lblLname,lblf,lbll; JLabel lblfVal,lbllVal; JTextField txtFname,txtLname; JButton btnInsert,btnUpdate,btnDelete,btnPrev,btnNext,btnClear; Connection con; ResultSet rs ; public static void main(String[] args) { JDBCCRUD obj = new JDBCCRUD(); obj.createUI(); obj.connect(); } private void createUI() { JFrame frame = new JFrame(“JDBC CREATE/READ/UPDATE/DELETE”); //Layout of Main Window Container c = frame.getContentPane(); c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS)); lblFname = new JLabel(“First Name :”); lblLname = new JLabel(“Last Name :”); txtFname = new JTextField(””,15);//To adjust width txtLname = new JTextField(); JPanel pnlInput = new JPanel(new GridLayout(4,2)); pnlInput.add(lblFname); pnlInput.add(txtFname); pnlInput.add(lblLname);

pnlInput.add(txtLname); btnInsert = new JButton(“Insert”); btnInsert.addActionListener(this); btnUpdate = new JButton(“Update”); btnUpdate.addActionListener(this); btnDelete = new JButton(“Delete”); btnDelete.addActionListener(this); btnClear = new JButton(“Clear”); btnClear.addActionListener(this); JPanel pnlButton = new JPanel(new GridLayout(1,4)); pnlButton.add(btnInsert); pnlButton.add(btnUpdate); pnlButton.add(btnDelete); pnlButton.add(btnClear); JPanel pnlAns = new JPanel(new GridLayout(4,2)); lblf = new JLabel(“First Name :”); lbll = new JLabel(“Last Name :”); lblfVal = new JLabel(””); lbllVal = new JLabel(””); pnlAns.add(lblf); pnlAns.add(lblfVal); pnlAns.add(lbll); pnlAns.add(lbllVal); btnPrev = new JButton(” > “); btnNext.setActionCommand(“Next”); btnNext.addActionListener(this); JPanel pnlNavigate = new JPanel(new GridLayout(1,2));

pnlNavigate.add(btnPrev); pnlNavigate.add(btnNext); frame.add(pnlInput); frame.add(pnlButton); frame.add(pnlAns); frame.add(pnlNavigate); frame.pack(); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent evt) { String cmd = evt.getActionCommand(); if(cmd.equals(“Insert”)) { insertData(); }else if(cmd.equals(“Update”)) { updateData(); }else if(cmd.equals(“Delete”)) { deleteData(); }else if(cmd.equals(“Prev”)) { previous(); }else if(cmd.equals(“Next”)) { next(); }else if(cmd.equals(“Clear”)) { clearControls(); }

} private void connect() { try { Class.forName(“com.mysql.jdbc.Driver”); con = DriverManager.getConnection(“jdbc:mysql://localhost/students”,“root”, ””); } catch(Exception e) { System.out.println(“Unable to connect”); } } private void disconnect() { try { con.close(); } catch(Exception e) {} } private void insertData() { try { String sql = “Insert Into StudentData(FName,LName) ” +“Values (’”+txtFname.getText()+”’,’”+txtLname.getText()+”’)”; Statement statement = con.createStatement(); statement.execute(sql); createMessageBox(“Inserted Successfully”); clearControls(); rs.close();

rs=null; } catch(Exception e) { createMessageBox(e.getMessage()); } } private void updateData() { try { String sql = “Update StudentData Set LName=’”+txtLname.getText()+“‘Where FName=’”+txtFname.getText()+”’”; Statement statement = con.createStatement(); int count=statement.executeUpdate(sql); createMessageBox(“Updated Successfully”); clearControls(); rs.close(); rs=null; } catch(Exception e) { createMessageBox(e.getMessage()); } } private void deleteData() { try { String sql = “delete ’”+txtFname.getText()+”’”;

from

StudentData

Statement statement = con.createStatement();

where

FName

=

//statement.execute(sql); statement.executeUpdate(sql); createMessageBox(“Record of “+txtFname.getText()+” Deleted Successfully”); clearControls(); rs.close(); rs=null; } catch(Exception e) { createMessageBox(e.getMessage()); } } private void previous() { try { if(rs == null) { String sql = “Select FName,LName from StudentData”;

Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABL rs = statement.executeQuery(sql); } if(rs.previous()&& !rs.isBeforeFirst()) { populateControls(); } } catch(Exception e) {

e.printStackTrace(); } } private void next() { try { if(rs == null) { String sql = “Select FName,LName from StudentData”;

Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONL rs = statement.executeQuery(sql); } if(rs.next() && !rs.isAfterLast())//After Last was giving invalid cursor state error { populateControls(); } } catch(Exception e) { e.printStackTrace(); } } private void createMessageBox(String msg) { JFrame frame = new JFrame(“Result”); JLabel lbl = new JLabel(msg); frame.add(lbl);

frame.setSize(200,200); frame.setVisible(true); } private void clearControls() { String empty = ””; txtFname.setText(empty); txtLname.setText(empty); lblfVal.setText(empty); lbllVal.setText(empty); } private void populateControls() { try{ lblfVal.setText(rs.getString(“fName”)); lbllVal.setText(rs.getString(“lName”)); txtFname.setText(lblfVal.getText()); txtLname.setText(lbllVal.getText()); } catch(SQLException e) { e.printStackTrace(); } } } O UTPUT JDBC Insert Operation

JDBC Update Operation

Message when u press Insert Button

Change Thakkar to Patel

Message when u press Update Button

JDBC Delete Operation Navigate to Sanjay Dhami Message when u press Record Update Button

PRACTICAL 13: WRITE A PROGRAM TO PRESENT A SET OF CHOICE FOR USER TO SELECT A PRODUCT & DISPLAY THE PRICE OF PRODUCT. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop a JDBC Program in JAVA using MySQL as backend. Learn How to handle JComboBox Control Events using ItemListener interface. L EARNING O UTCOMES Explain & Practice fetching values based on selection in JComboBox Events. A SSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. Following database and table created in MySQL Database: ProductInfo Table: ProductTable {ProductName Char(50), Price Number} ProductName

Price

CD

30

PenDrive

250

C ODE import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JComboBox; public class JDBCPriceDemo { JLabel lblItem; JComboBox cmbItemList; JLabel lblSelectedItem,lblItemPrice; String product; int price; Connection con; ResultSet rs1 ; ResultSet rs2; public static void main(String[] args) { JDBCPriceDemo obj = new JDBCPriceDemo();

obj.connect(); obj.createUI(); } private void createUI() { JFrame frame = new JFrame(“JDBC Product Price Demo”); frame.setLayout(new GridLayout(3,3)); lblItem = new JLabel(“Select Product to check price:”); JComboBox cmbItemList=new JComboBox(); try{ Statement stmt = con.createStatement(); String query = “SELECT * FROM ProductTable”; rs1 = stmt.executeQuery(query); while (rs1.next()) { cmbItemList.addItem(rs1.getString(“ProductName”)); } stmt.close(); rs1.close(); } catch(Exception e) {} lblSelectedItem = new JLabel(“Item:”); lblItemPrice = new JLabel(“Price:”); frame.add(lblItem); frame.add(cmbItemList); frame.add(lblSelectedItem); frame.add(lblItemPrice); ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { product= itemEvent.getItem().toString(); try { Statement st = con.createStatement();

rs2 = st.executeQuery(“SELECT Price FROM ProductTable WHERE ProductName = ’”+ product +”’”); if (rs2!=null) { rs2.next(); lblSelectedItem.setText(product.toString()); lblItemPrice.setText(String.valueOf(rs2.getInt(1))); rs2.close(); } } catch (SQLException ex) {} catch(Exception e) {} } }; cmbItemList.addItemListener(itemListener); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } private void connect() { try { Class.forName(“com.mysql.jdbc.Driver”); con = DriverManager.getConnection(“jdbc:mysql://localhost/ProductInfo”,“root”, ””); } catch(Exception e) { System.out.println(“Unable to connect”); }

} private void disconnect() { try { con.close(); } catch(Exception e) {} } } O UTPUT

EXERCISE: W RITE A JDBC PROGRAM TO IMPLEMENT THE L OGIN _I D F ORM USING JDBC. Code:

Output: W RITE A JDBC PROGRAM TO SELECT THE VALUES FROM THE DEPARTMENT TABLE . Code:

Output: W RITE A JDBC PROGRAM TO INSERT THE VALUES INTO THE STUDENT TABLE .

Code:

Output: W RITE A JDBC PROGRAM TO ALTER AND INSERT THE VALUES INTO TABLE . Code:

Output: W RITE A JDBC PROGRAM TO DELETE A RECORD BY TAKING THE INPUT FROM KEYBOARD . Code:

Output:

UNIT 4 G ENERAL O BJECTIVES After performing this practical student will be able to: Learn how to use Servlet to develop web applications. Develop and deploy a Servlet application using Apache web server. Learn how to read parameters in Servlet. Learn how to read initialization parameters using web.xml file. L EARNING O UTCOMES Explain Servlet concepts Practice Servlet programs. A SSUMPTIONS Oracle JDK installed, Apahe Web Server and Servlet API installed, configured and running. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured.

INTRODUCTION Servlets: For development of web basd components Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. This leaves you free to select a “best of breed” strategy for your servers, platforms, and tools. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls and receive all the benefits of the mature Java language, including portability, performance, reusability, and crash protection. Today servlets are a popular choice for building interactive Web applications. Thirdparty servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others. As we know that the servlet extends the HttpServlet and overrides the doGet () method which it inherits from the HttpServlet class. The server invokes doGet () method whenever web server receives the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse

object and this method throws the ServletException. Whenever the user sends the request to the server then server generates two objects’ first is HttpServletRequest object and the second one is HttpServletResponse object. HttpServletRequest object represents the client’s request and the HttpServletResponse represents the servlet’s response. Inside the doGet() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html It is the standard MIME content type for the html pages.After that it has used the method getWriter () of the response object to retrieve a PrintWriter object. To display the output on the browser we use the println () method of the PrintWriter class.

Inserting Data in Database table using Statement To accomplish our goal we first have to make a class named as ServletInsertingData, which must extends the abstract HttpServlet class, the name of the class should be such that other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method that takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we first need to call the method forName(), which is static in nature of the class Class. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method createStatement() of the Connection object which will return the Statement object. This object is used for executing a static SQL statement and obtaining the results produced by it. We have to insert a values into the table so we need to write a query for inserting the values into the table. This query we will write inside the executeUpdate() method of the Statement object. This method returns int value. If the record will get inserted in the table then output will show “record has been inserted” otherwise “sorry! Failure”.

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

For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking. Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.

Session tracking methods: 1. User authorization 2. Hidden fields 3. URL rewriting 4. Cookies 5. Session tracking API

Cookies Also known as browser cookies or tracking cookies, cookies are small, often encrypted text files, located in browser directories. They are used by web developers to help users navigate their websites efficiently and perform certain functions. Due to their core role of enhancing/enabling usability or site processes, disabling cookies may prevent users from using certain websites. Cookies are created when a user’s browser loads a particular website. The website sends information to the browser which then creates a text file. Every time the user goes back to the same website, the browser retrieves and sends this file to the website’s server. Computer Cookies are created not just by the website the user is browsing but also by other websites that run ads, widgets, or other elements on the page being loaded. These cookies regulate how the ads appear or how the widgets and other elements function on the page.

Cookie Class In JSP cookie is the object of the class javax.servlet.http.Cookie. This class is used to create a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie’s value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. The getCookies() method of the request object returns an array of Cookie objects. Cookies can be constructed using the following code: Cookie (java.lang.String name, java.lang.String value)

PRACTICAL 14: WRITE A SIMPLE SERVLET PROGRAM WHICH MAINTAINS A COUNTER FOR THE NUMBER OF TIMES IT HAS BEEN

ACCESSED SINCE IT’S LOADING; INITIALIZE THE COUNTER USING DEPLOYMENT DESCRIPTOR.

S PECIFIC O BJECTIVES After performing this practical student will be able to: Learn how to use SERVLET to maintain hit of web pages. L EARNING O UTCOMES Understand the servlet initialization parameters using web.xml file. A SSUMPTIONS Oracle JDK installed, Apache Web Serverinstalled and configured. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, path, classpath are configured. C ODE Index.html Hit Counter using Session Click to test Hit Counter for Servlet PageHitCounter.java import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.ServletException; import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse; import javax.servlet.ServletConfig; public class PageHitCounter extends HttpServlet{ private int hitCount; public void init(ServletConfig servletConfig) throws ServletException{ this.hitCount = Integer.valueOf(servletConfig.getInitParameter(“hit”)); } public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { // Set response content type response.setContentType(“text/html”); // This method executes whenever the servlet is hit // increment hitCount hitCount++; PrintWriter out=response.getWriter(); String title =“Total Number of Hits”; String docType= “\n”; out.println(docType+ “\n”+ “”+ title +”\n”+ “\n”+ “”+ title +”\n”+ “”+hitCount+”\n”+ “”); } public void destroy() { // This is optional step but if you like you // can write hitCount value in your database.

} } web.xml PageHitCounter PageHitCounter hit 0 PageHitCounter /PageHitCounter O UTPUT

PRACTICAL 15: CREATE A FORM PROCESSING SERVLET WHICH DEMONSTRATES USE OF COOKIES. S PECIFIC O BJECTIVES After performing this practical student will be able to: Learn how to use cookie in servlet to track sessions. L EARNING O UTCOMES Understand the use of cookie for session tracking. A SSUMPTIONS Oracle JDK installed, Apache Web Serverinstalled and configured. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, path, classpath are configured.

C ODE index.html Cookies Example in Servlets Cookies Example in Java First name: Last name: CookieExample.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class CookieExample extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { String fname=req.getParameter(“fname”); String lname=req.getParameter(“lname”); Cookie f=new Cookie(“first_name”,fname); Cookie l=new Cookie(“last_name”,lname);

res.addCookie(f); res.addCookie(l); res.setContentType(“text/html”); PrintWriter out=res.getWriter(); out.print(“Cookies Created Successfully!!!Click to Read cookies”); } } GetCookie.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class GetCookie extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { PrintWriter pw=res.getWriter(); pw.println(“”); Cookie[] c=req.getCookies(); for(Cookie k:c) { pw.println(k.getValue()); } pw.println(“”); } } Web.xml CookieExample CookieExample

CookieExample /CookieExample GetCookie GetCookie GetCookie /GetCookie O UTPUT

PRACTICAL 16: CREATE A FORM PROCESSING SERVLET WHICH DEMONSTRATES USE OF SESSIONS. S PECIFIC O BJECTIVES After performing this practical student will be able to: Learn how to use session in servlet to track sessions. L EARNING O UTCOMES Understand the use of session for session tracking. A SSUMPTIONS Oracle JDK installed, Apache Web Serverinstalled and configured. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, path, classpath are configured. C ODE index.htm

Get a Hi!!! Web.XMl SessionExample SessionExample SessionExample /SessionExample SessionTrack SessionTrack SessionTrack /SessionTrack SessionExample.java import javax.servlet.*;

import javax.servlet.http.*; import java.io.*; public class SessionExample extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String st=req.getParameter(“user”); HttpSession ses=req.getSession(); ses.setAttribute(“uname”,st); res.setContentType(“text/html”); PrintWriter out=res.getWriter(); out.print(“Session Created Successfully!!!Click to Read Session”); } } SessionTrack.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { PrintWriter pw=res.getWriter(); HttpSession ses=req.getSession(); String st=(String)ses.getAttribute(“uname”); pw.println(“ Hi “+st+””); } } O UTPUT



UNIT 5 G ENERAL O BJECTIVES After performing this practical student will be able to: Learn how to use JSP to develop web applications. Develop and deploy a JSP application using Apache web server. L EARNING O UTCOMES Explain JSP concepts Practice JSP programs. A SSUMPTIONS Oracle JDK installed, Apahe Web Server installed, configured and running. Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured.

INTRODUCTION JavaServer Pages (JSP) is a Java technology that allows software developers to dynamically generate HTML, XML or other types of documents in response to a Web client request. The technology allows Java code and certain pre-defined actions to be embedded into static content. The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way of extending the capabilities of a Web server. JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate a servlet in Java code that is then compiled by the Java compiler, or it may generate byte code for the servlet directly. JSP technology enables Web developers and designers to rapidly develop and easily maintain, information-rich, dynamic Web pages that leverage existing business systems. As part of the Java technology family, JSP technology enables rapid development of Webbased applications that are platform independent. JSP technology separates the user interface from content generation, enabling

designers to change the overall page layout without altering the underlying dynamic content

Create and Run a simple JSP program using tomcat Here I am going to explain for write create a simple jsp program and run that program in apache tomcat. This process has some steps. The following steps are based on windows operating system Java Server Pages are saved with .jsp extension. Installation and execution of JSP Follow these steps to run JSP Page: Step 1: Download and install latest Apache Tomcat and JAVA. Step 2: Create directory “JSPDemo” and apache D:\apache-tomcat8.0.15\webapps\JSPDemo directories under the webapps as shown here: Step 3: Create simple HelloWorld.jsp program using any editor like notepad: First JSP Page Hi, Step 4: Save this file as HelloWorld.jsp in D:\apache-tomcat8.0.15\webapps\JSPDemo\JSPApp directory:

Step 5: Before run this code, start apache tomcat as you have done following Section. Apache Tomcat port information Iamgivingthefollowinginformation 1.Tomcatportinformation 2.ChangeTomcatusernameandpassword(optional) 3 . Start, Stop and Restart tomcat 1 . Tomcat port information D:/ …/Tomcat6.0/conf/server.xml This file have default port number (During installation specified…) you can able to change that port number. Server.xml … … … … …

The connector tags have your tomcat port number. 2 . Change the tomcat manger username and password. (optional) If you want to change the tomcat username and password, then you edit the tomcatuser.xmlfile Here I showed, changed tomcat admin username and password Theusername:admin The password : admin123 3.Start , Stop and Resart tomcat If you have change (server.xml or tomcat-user.xml), then better you will restart your tomcat. Start or Restart (if already running) Apache Tomcat Server from command line D:\apache-tomcat-8.0.15\bin>startup.

4 : Check your username and password(optional) http://localhost:9999/ ThenClick TomcatManager andgiveusername(admin)andpassword(admin123). Ifsuccessfullylogin,thenusernameandpasswordperfecltlyset. Otherwise, check tomcat-users.xml file. Step 6: Set path, java_home, and classpath variable as required from command line. For example: SetJAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_25\ set PATH=%JAVA_HOME%;%PATH% setCLASSPATH=.;D:\apache-tomcat-8.0.15\lib\jsp-api.jar;D:\apache-tomcat8.0.15\webapps\JSPDemo; C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\

;

connector-java-5.1.34-bin %classpath% Step7 : Run HelloWorld.jsp program in browser using following link: http://localhost:9999/JSPDemo/HelloWorld.jsp Step 8: Observe the output:

mysql-



PRACTICAL 17: WRITE A SIMPLE JSP PROGRAM FOR USER REGISTRATION & THEN CONTROL WILL BE TRANSFER IT INTO SECOND PAGE. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop a JSP Program in JAVA. Learn How to handle page redirecting in Web browser. L EARNING O UTCOMES Explain & Practice Jsp scriplet tags and HTML tags. A SSUMPTIONS Oracle JDK, Apache-tomcat-8.0.15 installed. Editor Like notepad, Netbeans available for program development. Environment variables like JAVA_Home, Path, and Classpath are configured. C ODE Registration.jsp

Registration Form REGISTRATION FORM First Name Last Name Mobile

E-mail Gender Male Female Address City State

welcome.jsp Details Of User REGISTRATION HAS BEEN COMPLETED SUCCESSFULLY……. FirstName: LastName:

email: mobile : city : State: Gender: address: O UTPUT

PRACTICAL 18 :WRITE A SIMPLE JSP PROGRAM FOR USER LOGIN FORM WITH STATIC & DYNAMIC DATABASE. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop a JSP Program in JAVA. Learn How to handle static and dynamic database in Web browser. L EARNING O UTCOMES Explain & Practice how to access mysql database from JSP programme. A SSUMPTIONS Oracle JDK, Apache-tomcat-8.0.15 and wampserver2.2c-x32 installed. Editor Like notepad, Netbeans available for program development. Environment variables like JAVA_Home, Path, and Classpath are configured and copy mysql-connector jar file to folder C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext. C ODE ( A ) (a)

Write a simple JSP program for user login form with static database.

Login.jsp JSP Page

Login Page Signup Details Username: Password: Logincheck.jsp JSP Page

Home.jsp

pageEncoding=“UTF-8”

JSP Page Logout Logout.jsp JSP Page

Logout was done successfully. Error.jsp JSP Page Sorry Invalid Username or Password… O UTPUT

C ODE ( B ) (b)

Write a simple JSP program for user login form with dynamic database.

->Create logindatabase Database in MySQL. ->Create members Table under logindatabase Database. Members: first_name

last_name

email

uname

pass

regdate













login.jsp

JSP Example Login Here User Name Password Not Yet Registered!! Register Here

Logincheck.jsp Newregistration.jsp

Registration Enter Information Here First Name Last Name Email User Name Password

Already registered!! Login Here Registrationsubmit.jsp 0) {

response.sendRedirect(“welcome.jsp”); } else { response.sendRedirect(“login.jsp”); } %> Welcome.jsp Registration is Successful. Please Login Here Go to Login Success.jsp You are not logged in Please Login Welcome Log out OUTPUT:





PRACTICAL 19 :WRITE A JSP PROGRAM TO DISPLAY THE GRADE OF A STUDENT BY ACCEPTING THE MARKS OF FIVE SUBJECTS. S PECIFIC O BJECTIVES After performing this practical student will be able to: Develop a JSP Program in JAVA. Learn How to handle page redirecting in web browser. L EARNING O UTCOMES Explain & Practice Jsp scriplet tags and HTML tags. A SSUMPTIONS Oracle JDK, Apache-tomcat-8.0.15 installed. Editor Like notepad, Jcreator available for program development. Environment variables like JAVA_Home, Path, and Classpath are configured. C ODE Student Marks Student Grading System Enter Five Subject Marks out of 100

Subject Obtained Marks Total Marks C 100 Java 100 .Net 100 VB 100 DBMS

100 = 40 && percent =45 && percent =50 && percent =55 && percent=60 && percent =65 && percent=70 && percent =75 && percent =80 && percent =85 && percent Aggregate Marks Grade O UTPUT

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF