0% found this document useful (0 votes)
4 views178 pages

Chapter 6 GUI and JDBC

Assembly Level /Machine Organization 4

Uploaded by

yohannestagel5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views178 pages

Chapter 6 GUI and JDBC

Assembly Level /Machine Organization 4

Uploaded by

yohannestagel5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 178

Chapter 6:

Graphic User Interface(GUI) and JDBC

By Mekete T. KioT 2017 E.C


Contents

– Overview of GUI

– Elements of GUI: Component and container

– Concepts of GUI
 AWT

 Swings

Java Database Connectivity(JDBC)

– Overview of JDBC

– Setting up JDBC in SQL/Oracle

– Populating a database and Executing Queries

– Scrollable and Updateable Result Sets

– Java Servlets
GUI: Graphical User Interface

• A graphical user interface (GUI) presents a user-friendly mechanism

for interacting with an application.

• It gives an application a distinctive “look” and “feel.”

• Providing different applications with consistent, intuitive user

interface components allows users to be somewhat familiar with an

application, so that they can learn it more quickly and use it more

productively.

• GUIs are built from GUI components.

• These are sometimes called controls or widgets.


Cont…

• A GUI component is an object with which the user


interacts via the mouse, the keyboard or another form
of input, such as voice recognition
• Java GUI APIs: Java has two GUI packages,
1. the original Abstract Windows Toolkit (AWT) and
2. the newer Swing(Something WINdowing Graphics).

• When java was introduced, the GUI classes were bundled


in a library known as Abstract Windows Toolkit (AWT).
• It is Java’s original set of classes for building GUIs.
AWT(Abstract Window Toolkit)
• It uses peer components of the OS;

• It is heavy weight and uses the native operating system's window routines so
the visual effect is dependent on the run-time system platform.

• For every platform on which Java runs, the AWT components are
automatically mapped to the platform- specific components through their
respective agents, known as peers.

• It is not truly portable as it looks different and lays out inconsistently on


different OSs.

• AWT is a collection of GUI components (widgets) and other related services


required for GUI programming in Java.
Cont..

• The application's GUI components display


differently on each platform. In addition, AWT is
adequate for many applications but it is difficult to
build an attractive GUIs
Cont…
• AWT (Abstract Window Toolkit) is a package of various components and
utility classes used to create visual interfaces with Java.

• The classes are included in java.awt package.

• AWT has components such as Button, Label, Checkbox, Choice, List,


Container that derive from the java.awt.Component class.

• There are Window and Panel components that derive from the Container

class.

• The Frame and Dialog classes, which derive from the Window class, create

windows and host components such as Button and Label. The Panel class, on

the other hand, is used to host Button and Label components only.
Cont…
• AWT has java.awt.event package to handle
events such as click(MouseEvent),
write(KeyEvent) on components. The package
includes ActionEvent, MouseEvent,
MouseWheelEvent, KeyEvent, ItemEvent,
TextEvent, AdjustmentEvent, WindowEvent,
ComponentEvent, ContainerEvent, and
FocusEvent events.
Events

• Change in the state of an object is known as event


i.e. event describes the change in state of source.
• Events are generated as result of user interaction
with the graphical user interface components.
• For example, clicking on a button, moving the
mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are
the activities that causes an event to happen.
Types of Event

The events can be broadly classified into two categories:

• Foreground Events - Those events which require the direct interaction

of user.
 They are generated as consequences of a person interacting with the graphical

components in Graphical User Interface.

 For example, clicking on a button, moving the mouse, entering a character

through keyboard, selecting an item from list, scrolling the page etc.

• Background Events - Those events that require the interaction of end user

are known as background events.


 Operating system interrupts, hardware or software failure, timer expires, an

operation completion are the example of background events.


What is Event Handling?

• Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
• This mechanism have the code which is known as event handler that is
executed when an event occurs.
• Java Uses the Delegation Event Model to handle the events.
• The Delegation Event Model in Java GUI (Graphical User Interface) is a
design pattern used to handle events like button clicks, key presses, mouse
movements, etc., in Java's Abstract Window Toolkit (AWT) and Swing
frameworks.
• This model defines the standard mechanism to generate and handle the
events.
• Let's have a brief introduction to this model.
Cont...
• The Delegation Event Model has the following key participants namely:
• Source - The source is an object on which event occurs. Source is responsible
for providing information of the occurred event to it's handler. Java provide as
with classes for source object. This is the GUI component that generates events
(e.g., a Button).
• Event Object – This object encapsulates information about the event (e.g.,
ActionEvent).
• Listener - It is also known as event handler.
 Listener is responsible for generating response to an event.
 From java implementation point of view the listener is also an object.
 Listener waits until it receives an event.
 Once the event is received , the listener process the event an then returns
 This is an interface that defines methods to handle specific types of events (e.g.,
ActionListener).
Cont..

 When an event occurs (e.g., a user clicks a button), the event source creates
an event object.
 This object is sent to all registered listeners for that source.
 Each listener has an event handler method that processes the event.
import javax.swing.*;
import java.awt.event.*;
public class MyButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Delegation Event Model Example");
JButton button = new JButton("Click Me");
// 3. Event Listener (interface) is implemented here using an anonymous inner class
// 4. Event Handler is the body of the actionPerformed() method
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 4. Event Handler
System.out.println("Button was clicked!");
}
});
frame.add(button);
Cont..
Component Example
1. Event Source button (an instance of JButton) – it generates the event
ActionEvent e – passed to the actionPerformed() method when
2. Event Object
the event occurs
3. Event Listener new ActionListener() – this anonymous inner class is a listener
System.out.println("Button was clicked!"); – this code responds
4. Event Handler
to the event
Cont...

The benefit of this approach is that the user interface logic is


completely separated from the logic that generates the event.
The user interface element is able to delegate the processing
of an event to the separate piece of code.
In this model ,Listener needs to be registered with the source
object so that the listener can receive the event notification.
This is an efficient way of handling the event because the
event notifications are sent only to those listener that want to
receive them.
Cont...
Steps involved in event handling
 The User clicks the button and the event is generated.

 Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.

 the method is now get executed and returns.

Points to remember about listener


 In order to design a listener class we have to develop some listener interfaces.

These Listener interfaces forecast some public abstract callback methods which

must be implemented by the listener class.

 If you do not implement the any if the predefined interfaces then your class can

not act as a listener class for a source object.


Callback Methods

• These are the methods that are provided by API provider and are defined by the

application programmer and invoked by the application developer.

• A callback method is a method that you pass as an argument to another method so it

can be "called back" (i.e., invoked) later—usually when a specific event occurs or

a task completes.

• In Java, callbacks are typically implemented using interfaces, especially in GUI

and event-driven programming.

• All such callback methods are provided in listener interfaces.

• If a component wants some listener will listen to it's events the source must register

itself to the listener.

• In Java GUI programming (AWT/Swing), the callback method is usually the


Example

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

// This is the callback method

System.out.println("Button clicked");

}});

Event Source

 button is a JButton instance.

 It is the event source, meaning it generates an ActionEvent when clicked.

Event Listener

 new ActionListener() { ... } is an anonymous class that implements the ActionListener

interface.

 You're registering this listener to the button using addActionListener(...).


• Callback Method

 public void actionPerformed(ActionEvent e) is the callback method.

 It is automatically called by the Java event system when the button is

clicked.
 The ActionEvent e object contains details about the event (like the

source, timestamp, etc.).

• ActionEvent

 This object (e) is automatically created and passed by the system when

the event (button click) happens.


 It holds information about the event, like what component triggered it.
• Flow of the above
 You click the button.

 button (the event source) fires an ActionEvent.

 The system checks all registered listeners.

 It finds your ActionListener.

 It calls back the actionPerformed(ActionEvent e) method


you defined.
 Your code in the method runs: System.out.println("Button
clicked");
Example
import java.awt.*;

import java.awt.event.*;

public class AwtControlDemo {

//declaring variable

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

//create constructor to prepare your frame

public AwtControlDemo(){

prepareGUI();

}
Cont..
private void prepareGUI(){ statusLabel.setSize(350,100);

mainFrame = new Frame("Java AWT controlPanel = new Panel();

Examples"); controlPanel.setLayout(new FlowLayout());

mainFrame.setSize(400,400); mainFrame.add(headerLabel);

mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.add(controlPanel);

mainFrame.addWindowListener(new mainFrame.add(statusLabel);
WindowAdapter() { mainFrame.setVisible(true); }
public void windowClosing(WindowEvent

windowEvent){

System.exit(0); } });

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

tatusLabel.setAlignment(Label.CENTER);
Example
private void showEventMethod(){ cancelButton.setActionCommand("Cancel");

headerLabel.setText("Control in action: okButton.addActionListener(new

Button"); ButtonClickListener());

//creating controller submitButton.addActionListener(new

Button okButton = new Button("OK"); ButtonClickListener());

Button submitButton = new cancelButton.addActionListener(new

Button("Submit"); ButtonClickListener());

Button cancelButton = new //adding created controller in the frame

Button("Cancel"); controlPanel.add(okButton);

okButton.setActionCommand("OK"); controlPanel.add(submitButton);

controlPanel.add(cancelButton);

submitButton.setActionCommand("Submit"); mainFrame.setVisible(true); }
Cont..
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button clicked.");
}
else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
}
else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
Cont...
• When You run it and click the button you will get
the following
Swings
• Swing is a part of Java Foundation Classes (JFC) that is used to create Java-

based Front end GUI applications.


• Swing: is designed to solve AWT’s problems (since Java 2).

• It is 99% java; It is lightweight components as drawing of components is done in java.

• Swing GUI components allow you to specify a uniform look-and-feel for your application

across all platforms.

• It also lays out consistently on all OSs.

• It has much bigger set of built-in components and uses AWT event handling.

• Swing is built “on top of” AWT, so you need to import AWT and use a few things from it.

• Swing is bigger.

• Swing is more flexible and better looking.

• Swing and AWT are incompatible. Thus, you can use either, but you can’t mix them .
Cont…
•The latest JavaFX, which was integrated into JDK 8, was meant to replace Swing.

•JavaFX was moved out from the JDK in JDK 11, but still available as a separate

module.
• Basic components/controls are practically the same in AWT and SWINGS. For

example:
AWT: Button b = new Button ("OK");

Swing: JButton b = new JButton("OK");

• Swing gives far more options for everything (buttons with pictures on them, etc.).

• AWT classes are contained inside package java.awt while Swing classes are

located in package javax.swing. Below is demonstration of Java GUI ApIs

diagrammatically.
Cont…
AWT Swings
Type Type
AWT components are heavyweight Swing components are lightweight
Platform Dependency Platform Dependency
AWT is platform dependent Swing is platform independent
Display Display
Moreover, AWT does not support a pluggable Swing supports a pluggable look and feel. This is
look and feel. also an important difference between AWT and
Components Swing in Java
AWT has Basic components Components
Speed Also, Swing has more advanced components than
execution of AWT is slower. AWT.
MVC Speed
AWT supports MVC but it does not enforce it by default. Swing executes Faster
MVC
Swing supports MVC pattern
Cont…

• Model-View Controller(MVC)
• In OOP, MVC is the name of methodology or design pattern for

successfully and efficiently relating the user interface to the underlying

data model.
• MVC (Model-View-Controller) is a design pattern that helps organize

code by separating an application into three parts:


Part Responsibility

Model Manages the data and business logic

View Displays the user interface

Controller Handles user input and updates the model/view


Implementation of MVC

• We are going to create a Student object acting as a model.


• StudentView will be a view class which can print student
details on console and
• StudentController is the controller class responsible to store
data in Student object and update view StudentView
accordingly.
Cont…
• Step1:- Create Model
Student.java
public class StudentModel {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo; }
public void setRollNo(String rollNo) {
this.rollNo = rollNo; }
public String getName() {
return name; }
public void setName(String name) {
this.name = name;
}}
Cont…
Step 2:-Create View.

StudentView.java

public class StudentView {

public void printStudentDetails(String studentName, String studentRollNo){

System.out.println("Student: ");

System.out.println("Name: " + studentName);

System.out.println("Roll No: " + studentRollNo);

}}
Step 3:-Create Controller.
StudentController.java
public class StudentController {
private StudentModel model;
private StudentView view;
public StudentController(StudentModel model, StudentView view){
this.model = model;
this.view = view; }
public void setStudentName(String name){
model.setName(name); }
public String getStudentName(){
return model.getName(); }
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo); }
public String getStudentRollNo(){
return model.getRollNo(); }
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}}
Cont…
Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.Here is th driver class
containing the main method
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the database
StudentModel model = new StudentModel();
//Create a view : to write student details on console
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
//update model data
controller.setStudentName("John");
controller.updateView();
}
private static Student retriveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}
Difference Between AWT and Swings
AWT Swings
Memory Space Memory Space
Moreover, AWT components require Swing components do not require much
more memory space memory space
Package Package
The programmer has to import the the programmer has to import
javax.awt package to develop an AWT- javax.swing package to write a Swing
based GUI. application
Component classes and Helper class

A Component class is a UI element that is part of the graphical interface,


directly used to create the layout and interactions.
GUI Container classes:
 A GUI is built by putting components/controls into containers.
 Thus, container is used to group components.

Frames, Panels and applets are examples of containers.


Important Container classes are JFrame, JApplet, JDialog and JPanel.
Frame:
 A resizable, movable window with title bar and close button.
 Usually it contains JPanels. It is a container that holds other Swing user-

interface components in Java GUI applications.


Cont…

JPanel:
 JPanel is a region internal to a JFrame or another JPanel.

 It is used for grouping components together.


 JPanel is optionally bounded by a visible border .
 It lives inside some enclosing Container.

 Panels can be nested, that is, you can place panels inside a container that includes a panel.

 In fact, every frame has at least one pane, the default “Content Pane”.

GUI Component classes:


 GUI Components or Controls (also known as "widgets") are the basic user interface elements

the user interacts with.


 These include labels, buttons and text fields.

 The visual arrangement of the components depends on the container's layout (which are part

of helper classes)
Cont…

Here is a list of controls in the javax.swing package:


 Input Components
 Buttons ( JButton, JRadioButtons, JCheckBox

 The visual arrangement of the components depends on the container's


layout (which are part of helper classes)
 Text (JTextField, JTextArea) 
 Menus (JMenuBar, JMenu, JMenuItem)
 Sliders (JSlider)
 JComboBox (uneditable) (JComboBox)
 List (Jlist )

 Information Display Components 


 JLabel
 Progress bars (JProgressBar)
 Tool tips (using JComponent's setToolTipText(s) method
Cont…

 Choosers
 File chooser (JFileChooser)
 Color chooser (JColorChooser)

 More complex displays


 Tables (JTable) 
 Trees (JTree)
GUI helper classes:
 Helper classes are used to describe the properties of GUI components.
 It encompasses the classes for graphics context, colors, fonts and dimension
Graphics: It is an abstract class that provides a graphical context for drawings
strings, lines, and simple shapes.
Color: It deals with the colors of GUI .
Cont…

For example, we can specify background colors in components like


JFrame and JPanel while we can specify colors of lines, shapes and etc.
Font: It specifies fonts for the text and drawings on GUI components.
Font is available on the java.awt package. Example:
panel1.setFont(new Font("Serif",Font.TRUETYPE_FONT +
Font.ITALIC + Font.BOLD,20));
LayoutManager: is an interface whose instances specify how
components are arranged in a container.
There are different types of layouts. FlowLayout, GridLayout and
BorderLayout are three examples of the layouts. These layouts are
found in the java.awt package of JDK API.
Cont…

Let us see an example using one of these three layout types.


LayoutManager lay_out = new FlowLayout();
JFrame Frame_based_container = new JFrame(“I am a container");
Frame_based_container.setLayout(lay_out);
setLayout(new FlowLayout());//default one
setLayout(new FlowLayout(FlowLayout.LEFT));
setLayout(new FlowLayout(FlowLayout.LEFT, 20,30));
•It should be noted that before adding components to a certain container, the layout
must be first set depending on the desired arrangement of the containers or
components inside the container.
•Nowadays, Java GUI focuses on Swing GUI components and Swing Containers.
• At the meantime, the helper classes are used from AWT.
Steps in building GUI Application

• Step 1.Creating GUI Containers:


• Step 2. Create some more Components (such as buttons and text
areas
• Step 3. Add your components to your display area: choose a layout
manager
Steps in building GUI Application

1.Creating GUI Containers:


Create a container that could contain components or other containers.
We need to create either a frame or an applet to hold the user-interface components.
Frame:
 It is an independent window that has decorations such as a border, a title and
buttons for closing, minimizing and maximizing the window.
Frame is a window that is not contained inside another window.
A frame can be moved around on the screen independently of any other GUI
windows.
Applications with a GUI typically use at least one frame.
Frame is the basis to contain other user interface components in Java GUI
applications.
The JFrame class can be used to create windows.
Cont…

The following statement creates a window with title “My First JFrame”
JFrame frame = new Jframe(“My First Jframe”)
The JFrame class has the following two constructors:
JFrame(): This constructor constructs a new frame with no title and it is initially
invisible.
JFrame(String title): This constructor constructs a new, initially invisible frame with
specified title.
Some of the methods of JFrame class are described here in class diagram
Cont…
• setBounds(int x, int y, int width,Int height) : It is another method of JFrame class that

encompasses the methods setLocation(int x, int y) and setSize(int width, int height). It

specifies the size of the frame and the location of the upperbleft corner.

• This puts the upper left corner at location (x, y), where x the number of pixels from the left

of the screen and y is the number from the top of the screen. height and width are as

before.

• public void setDefaultCloseOperation(int mode): It is a method of JFrame class that is

used to specify one of several options for the close button. Every JFrame instance window

has a close button. We can program how the window reacts when this close button is

clicked. Use one of the following constants to specify your choice:


 JFrame.EXIT_ON_CLOSE: exit the application.

 JFrame.HIDE_ON_CLOSE: Hide the frame, but keep the application

 running. JFrame.DO_NOTHING_ON_CLOSE: Ignore the click.


Cont…
Example: Here is a java code that creates a window/frame with the specified title,
location, size, frame visibility and default close operation. Let you go through the

code and understand what each line of the code means .

import javax.swing.*;

public class JFrameSample{

public static void main(String[] args){

Jframe frame = new JFrame(“First JFrame");

frame.setSize(400, 300);

frame.setLocationRelativeTo(null);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);
Cont…
Here is another way of writing the above code (by extending Jframe)
import javax.swing.JFrame;

public class Simple extends JFrame {

public Simple() { setSize(300,200);

setTitle("First JFrame");

setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true); }

public static void main(String[] args) {

Simple simple = new Simple(); } }


Cont…
2. Create some more Components (such as buttons and text areas)

JButton:

A button is a component that triggers an action event when clicked.

A JButton component can be created using one of the following constructor


 JButton(): Creates a default button with no text and icon.

 JButton(Icon icon): Creates a button with an icon.  JButton(String text): Creates a button

with text.
 JButton(String text, Icon icon): Creates a button with text and an icon.

JButton class has different methods including the following:


 public void setText(String text) : Sets the button's text.
 public String getText(): Returns the button's text.
 public void setEnabled(boolean b) : Enables (or disables) the button.
 public void setSelectedIcon(Icon selectedIcon): Sets the selected icon for the button
Cont…
 public boolean isSelected() : Returns the state of the button. True if the toggle button is selected, false if it's

not

Here two alternative examples that create a JButton component with text “Click Here”. JButton button= new

JButton(); button.setText(“Click Here”);

OR

JButton button= new JButton(“Click Here");

JLabel: A label is a display area for a short text(a non-editable), an image, or both.

A JLabel component can be created using one of the following constructors: •


 JLabel(): Creates a default label with no text and icon.

 JLabel(String text): Creates a label with text.

 JLabel(Icon icon): Creates a label with an icon.

 JLabel(String text, int horizontalAlignment): Creates a label with a text and the specified horizontal alignment.

 JLabel(Icon icon, int horizontalAlignment): Creates a label with an icon and the specified horizontal alignment.

 JLabel(String text, Icon icon, int horizontalAlignment): Creates a label with text, an icon, and the specified horizontal

alignment.
Cont…
JLabel component has various methods including the following:
 public String getText(): Returns a string containing the text in the label component

 public void setText(String): Sets the label component to contain the string value

 public Icon getIcon(): Returns the graphic image (icon) that the label displays.

 public void setIcon(Icon icon): Defines the icon this component will display. If the
value of icon is null, nothing is displayed.

For example, JLabel can be used as follows.


// Create an image icon from image file
ImageIcon icon = new ImageIcon("image/grapes.gif");
// Create a label with text, an icon, with centered horizontal alignment
JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER )
Cont…
//Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5)

Example:- Create A Jframe with button labeled with Click Here


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;
public class JavaFrame {

public static void main(String[] args) {

JFrame frame = new JFrame("My First Frame!");

frame.setSize(220, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container contentPane = frame.getContentPane();

contentPane.setLayout(null);

JButton button = new JButton(“Click Here!");

button.setLocation(30, 30);

button.setSize(150, 100);

contentPane.add(button);

frame.setVisible(true); }}
Cont…
Swing Hello World with Events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Toolkit.getDefaultToolkit().beep(); }}
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World!");
frame.setSize(220, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
Container contentPane = frame.getContentPane();
contentPane.setLayout(null);
JButton button = new JButton("Hello World!");
button.addActionListener(new MyActionListener());
button.setLocation(30, 30);
button.setSize(150, 100);
contentPane.add(button);
frame.setVisible(true); }}
Cont…
import java.awt.*; contentPane.add(button);
import java.awt.event.*; JLabel lblFname= new JLabel("First Name");
import javax.swing.*; JTextField txtFname = new JTextField("",10);
class MyActionListener implements ActionListener { JLabel lblLname= new JLabel("Last Name");
public void actionPerformed(ActionEvent e) { //Text field to receive 10 line text
Toolkit.getDefaultToolkit().beep(); JTextField txtLname = new JTextField("",10);//
}} //======================
public class JavaFrame { lblFname.setSize(150,100);
public static void main(String[] args) { lblFname.setLocation(10,0);
//creating a frame with Title My First Frame txtFname.setSize(100,50);
JFrame frame = new JFrame("My First Frame!"); txtFname.setLocation(80,10);
frame.setSize(220,200);//setting frame 220 by 200 contentPane.add(lblFname);
//Set Close button contentPane.add(txtFname);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL //==========================
OSE); lblLname.setSize(150,100);
//creating Frame container lblLname.setLocation(10,40);
Container contentPane = frame.getContentPane(); txtLname.setSize(100,50);
//container layout be null txtLname.setLocation(80,60);
contentPane.setLayout(null); contentPane.add(lblLname);
//creating button contentPane.add(txtLname);
JButton button = new JButton("Click hear!"); //==========================
button.setLocation(80,120); frame.setVisible(true); } }
button.setSize(50,50);
button.addActionListener(new MyActionListener());
JTextField
JTextField: A text field is a box that contains a line of text.
The user can type text into the box and the program can get it and then use it as data.
The program can write the results of a calculation to a text field.
Text fields are useful in that they enable the user to enter in variable data (such as a name or a
description).
JTextField is swing class for an editable text display.
JTextField components can be created using one of the following constructors:

JTextField(): it creates a default empty text field with number of columns set to 0.

 JTextField(int columns): it creates an empty text field with the specified number
of columns.
JTextField(String text): it creates a text field initialized with the specified text.

 JTextField(String text, int columns): it creates a text field initialized with the
specified text and the column size.
Cont…
JTextfield class has the following method
public String getText(): returns the string from the text field.

public void setText(String text): puts the given string in the text field.

public void setEditable(boolean editable): enables or disables the text field to be


edited. By default, editable is true.
public void setColumns(int): sets the number of columns in this text field. The
length of the text field is changeable.
Public void select(int selectionStart, int selectionEnd): Selects the text between
the specified start and end positions.
 public String getSelectedText(): Returns the text value that has been highlighted in
the text field.
public void append(String value): Appends the text value of the string to the
already existing text in the component
Cont…
JPasswordField: Allows the editing of a single line of text where the view
indicates something was typed, but does not show the original characters.
JPasswordField component can be created using one of the following
constructors: 
JPasswordField(): Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column width
 JPasswordField(int columns): Constructs a new empty JPasswordField with the specified
number of columns
JPasswordField(String text): Constructs a new JPasswordField initialized with the specified
text.
JPasswordField(String text, int columns) : Constructs a new JPasswordField initialized
with the specified text and columns.
Cont…
JTextArea: If you want to let the user enter multiple lines of
text, you cannot use text fields unless you create several of them.
The solution is to use JTextArea class, which enables the user
to enter multiple lines of text.
JTextArea components can be created using one of the
following constructors:
JTextArea(int rows, int columns): creates a text area with the specified number
of rows and columns
JTextArea(String s, int rows, int columns): es a text area with the initial text
and the number of rows and columns specified
Cont…
JCheckBox: It is a widget that has two states. On and Off.
It is a box with a label. If the checkbox is checked, it is represented by a tick in a
box. JCheckBox component can be created using one of the following constructors:
oJCheckBox() :creates an initially unselected check box button with no text, no icon
oJCheckBox(Icon icon) : creates an initially unselected check box with an icon
oJCheckBox(Icon icon, boolean selected) : creates a check box with an icon and specifies whether or
not it is initially selected. 
oJCheckBox(String text) : creates an initially unselected check box with text.
oJCheckBox(String text,boolean selected): creates a check box with text and specifies whether or not it
is initially selected.
o JCheckBox(String text,Icon icon) : creates an initially unselected check box with the specified text
and icon.
oJCheckBox(String text, Icon icon, Boolean selected) : creates a check box with text and icon, and
specifies whether or not it is initially selected.
Cont…
• Example: JCheckBox checkBox3 = new
JCheckBox("PHP");
import javax.swing.*;
import java.awt.*; checkBox3.setBounds(300,100,50,50);
import java.awt.event.*; f.add(checkBox1);
public class Simple extends JFrame { f.add(checkBox2);
Simple(){ f.add(checkBox3);
JFrame f= new JFrame("CheckBox
Example"); f.setSize(500,400);
JCheckBox checkBox1 = new f.setLayout(null);
JCheckBox("C++",true);
f.setVisible(true);
}
checkBox1.setBounds(100,100,50,50);
public static void main(String[] args){
JCheckBox checkBox2 = new
JCheckBox("Java"); new Simple();
}
checkBox2.setBounds(200,100,50,50); }
Cont…
Java JCheckBox Example with f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
ItemListener public void itemStateChanged(ItemEvent e) {
package javaframe;
import javax.swing.*; label1.setText("C++ Checkbox: "
import java.awt.*; +
import java.awt.event.*; (e.getStateChange()==1?"checked":"unchecked"));
public class Simple extends JFrame { }
Simple(){ });
JLabel label1=new JLabel(); checkBox2.addItemListener(new ItemListener() {
JFrame f= new JFrame("CheckBox Example"); public void itemStateChanged(ItemEvent e) {
JCheckBox checkBox1 = new JCheckBox("C++",true);
checkBox1.setBounds(100,100,50,50); label1.setText("Java Checkbox: "
JCheckBox checkBox2 = new JCheckBox("Java"); +
(e.getStateChange()==1?"checked":"unchecked"));
checkBox2.setBounds(200,100,50,50);
}
JCheckBox checkBox3 = new JCheckBox("PHP");
});
checkBox3.setBounds(300,100,50,50);
}
label1.setBounds(200,0,100,50);
f.add(checkBox1);
public static void main(String[] args){
f.add(checkBox2);
new Simple();
f.add(checkBox3);
f.add(label1);
}
f.setSize(400,400);
}
f.setLayout(null);
CheckBox full example
import javax.swing.*; }
import java.awt.event.*; public void actionPerformed(ActionEvent e){
public class CheckBoxExample extends JFrame implements float amount=0;
ActionListener{ String msg="";
JLabel l; if(cb1.isSelected()){
JCheckBox cb1,cb2,cb3; amount+=100;
JButton b; msg="Pizza: 100\n";
CheckBoxExample(){ }
l=new JLabel("Food Ordering System"); if(cb2.isSelected()){
l.setBounds(50,50,300,20); amount+=30;
cb1=new JCheckBox("Pizza @ 100"); msg+="Burger: 30\n";
cb1.setBounds(100,100,150,20); }
cb2=new JCheckBox("Burger @ 30"); if(cb3.isSelected()){
cb2.setBounds(100,150,150,20); amount+=10;
cb3=new JCheckBox("Tea @ 10"); msg+="Tea: 10\n";
cb3.setBounds(100,200,150,20); }
b=new JButton("Order"); msg+="-----------------\n";
b.setBounds(100,250,80,30); JOptionPane.showMessageDialog(this,msg+"Total:
b.addActionListener(this); "+amount);
add(l);add(cb1);add(cb2);add(cb3);add(b); }
setSize(400,400); public static void main(String[] args) {
setLayout(null); new CheckBoxExample();
setVisible(true); }
setDefaultCloseOperation(EXIT_ON_CLOSE); }
Cont…
• When you run the above file and select Items
and click on order button you will have the
following
Creating Menu Driven Java Application
• We can create a menu driven application in java from which we can choose an
activity.

• There are three important swing components for the development of menu
driven application.

• These are JMenuBar, JMenu and JMenuItem.


 JMenuBar: It is used to create the menu bar. Menu bar is created using the

constructor JMenubar().

For example, we may create a menu bar as follows.

JMenuBar jmb = new JMenuBar();

• Once a menu bar is created, the menu bar is going to be embedded onto the
container frame using the method setJMenuBar(JMenuBar mbr).
Cont…
 JMenu: It is used to create menu or submenus.

 The constructor JMenu(String name) can be used to create a

menu/submenu.

For example, JMenu fileMenu = new JMenu(“File”).


 Once menus are created using JMenu, these menus can be added onto the

menu bar using the function add(JMenu menu).


 Assume we have created two menu component file and edit as follow.
JMenu fileMenu = new JMenu(“File”).

JMenu editMenu = new JMenu(“Edit”).

We can add these menu components to the menu bar we created earlier as follow
Jmb.add(fileMenu);

Jmb.add(editMenu)
Cont…
 JMenuItem: This component is used to add menu items under menu components.
 The constructor JMenuItem(String item) is used to create such items.
 Once the items are created the method add(JMenuItem item) can be used to add the
item to a menu component.
For example, let us create two menu items under the file menu.
JMenuItem menuItemNew = new JMenuItem(“New”);
JMenuItem menuItemOpen = new JMenuItem(“Open”);
fileMenu.add(menuItemNew);
fileMenu.add(menuItemOpen);

 Creating submenu under a menu: It is possible to have a menu under another


menu, that is, creating a submenu under a menu.
 First, the submenu will be created using the JMenu constructor. Then, we will use
the method add(JMenu menu) to add the submenu under a menu.
 Let us observe the complete code of the following example and notice how a
submenu is added to a men
Cont…
openMenu.add(openFRomNet);
import java.awt.event.ActionEvent;
fileMenu.add(openMenu);
import java.awt.event.ActionListener;
fileMenu.add(closeWindow);
import javax.swing.*;
closeWindow.addActionListener(new ActionListener(){
public class ClassAtMenuing {
@Override
public static void main(String[] args) {
public void actionPerformed(ActionEvent e) {
JFrame myEditor = new JFrame("My Editor ++");
JOptionPane.showMessageDialog(null, "You are closing thed editor");
JMenuBar myMenuBar = new JMenuBar();
myEditor.dispose();
myEditor.setJMenuBar(myMenuBar);
}
//Create the Menus
});
JMenu fileMenu = new JMenu("File");
//add menu into the menubar
JMenu editMenu = new JMenu("Edit");
myMenuBar.add(fileMenu);
JMenu developersMenu = new JMenu("The Develpers");
myMenuBar.add(editMenu);
//add meu items under File
myMenuBar.add(developersMenu);
JMenuItem itemSave = new JMenuItem("Save");
myEditor.setBounds(100, 150, 400, 300);
JMenuItem closeWindow = new JMenuItem("Exit");
myEditor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JMenuItem itemOpen = new JMenuItem("Open");
myEditor.setVisible(true);
fileMenu.add(itemSave);
}
//adding Submen
}
JMenu openMenu = new JMenu("Open");
//items under open
JMenuItem openFromLocalDisk = new JMenuItem("Open from local
disk");
JMenuItem openFRomNet = new JMenuItem("Open from the network");
//add the items to the open JMenu
openMenu.add(openFromLocalDisk);
Cont…
import javax.swing.*; frame.setJMenuBar(menuBar);
import java.awt.*; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
import java.awt.event.*; frame.setSize(400,400);
class Menu implements ItemListener{ frame.setVisible(true); }
JCheckBoxMenuItem apple; public static void main(String args[]){
JCheckBoxMenuItem berry; Menu menuGUI = new Menu(); }
JCheckBoxMenuItem carrot; public void itemStateChanged(ItemEvent e) {
Menu(){ Object source = e.getItemSelectable();
JFrame frame = new JFrame(); if (e.getStateChange() == ItemEvent.SELECTED) {
JMenuBar menuBar = new JMenuBar(); if (source == apple) {
JMenu menu = new JMenu("A JMenu"); JOptionPane.showMessageDialog(null,"Apple
JMenu menu2 = new JMenu("Computer"); Selected");
JMenuItem itemSave = new JMenuItem("Hardware"); } else if (source == berry) {
JMenuItem closem=new JMenuItem("Software"); JOptionPane.showMessageDialog(null,"Berry
menu2.add(itemSave); Selected");
menu2.add(closem); } else if (source == carrot) {
apple = new JCheckBoxMenuItem("apple"); JOptionPane.showMessageDialog(null,"Carrot
Selected");
berry = new JCheckBoxMenuItem("berry");
}
carrot = new JCheckBoxMenuItem("carrot");
apple.addItemListener(this);
} else {
berry.addItemListener(this);
if (source == apple) {
carrot.addItemListener(this);
System.out.println("Apple DE-Selected");
menu.add(apple);
} else if (source == berry) {
menu.add(berry);
System.out.println("Berry DE-Selected");
menu.add(carrot);
} else if (source == carrot) {
menuBar.add(menu);
System.out.println("Carrot DE-Selected");
menuBar.add(menu2);
} } }}
//frame.setJMenuBar(menuBar);
Cont…

• Java JRadioButton:- The JRadioButton class


is used to create a radio button.
• It is used to choose one option from multiple
options.
• It is widely used in exam systems or quiz.
• It should be added in ButtonGroup to select one
radio button only
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
f=new JFrame();
JRadioButton r1=new JRadioButton(" Male");
JRadioButton r2=new JRadioButton(“ Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public static void main(String[] args) {
new RadioButtonExample(); } }
Cont…
Java JComboBox
• The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits JComponent class. Commonly
used Constructors
Cont…
Example
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample(); } }
Cont…

• Java Jtable
 The JTable class is used to display data in tabular form. It is
composed of rows and columns Commonly used Constructor
Cont…
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"}, 7. {"102","Jai","780000"}, 8. {"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Cont…
Step 3:- Add your components to your display area: choose a
layout manager
 Each JFrame contains a content pane.

 A content pane is an instance of java.awt.Container.

 The GUI components such as buttons are placed in the content

pane in a frame.
 Prior to JDK 1.5, you have to use the getContentPane() method

in the JFrame class to return the content pane of the frame, and
then invoke the content pane’s add method to place a
component into a content pan
Cont…
 This was cumbersome, JDK 1.5 allows you to place the
components to the content pane by invoking a frame’s add
method.
 This new feature is called content pane delegation.
 Strictly speaking, a component is added into the content pane
of the frame.
 But for simplicity we say that a component is added to a
frame.
 When a component is added to a container, a reference to the
component is added to the list of components in the container.
 Below are four alternatives to add a button with text “OK”
into a frame instance, “frame”.
 We assume that the frame has been instantiated somewhere
Cont…
Example1:Jbutton jbt=new Jbutton(“OK”);
frame.getContentPane().add(jbt);
Example2:frame.getContentPane().add(new JButton("OK"));
Example 3: JButton jbt = new Jbutton(“OK”) frame.add(jbt);

Example 4: frame.add(new JButton("OK"));


Below is a full java code that adds the button to the
frame (following the approach employed by example 3
above)
Layout Management:
• Layouts tell Java where to put components in containers (JPanel, content

pane, etc).

• Layout manager is created using LayoutManager class.

• Every layout manager class implements the LayoutManager class.

• Each layout manager has a different style of positioning components.

• If you don't specify otherwise, the container will use a default layout

manager.

• Every panel (and other container) has a default layout, but it's better to set

the layout explicitly for clarity.

• Layout managers are set in containers using the

setLayout(LayoutManager) method.
Cont..
• Example: assume we have a Jframe instance called container.
If we are going to add controls inside this container and if we are
interested on the flowlayout, we can set as follows
LayoutManager layoutManager = new FlowLayout();
container.setLayout(layoutManager); OR
container.setLayout(new FlowLayout());
Java supplies several layout managers including
FlowLayout: The Simplest layout manager (the default one)Components
are placed left to right in the order in which they were added. When one row is
filled, a new row is started.
Cont..
• FlowLayout has the following possible constructors.

GridLayout:
The GridLayout manager divides the container up into a given number of rows and
columns.
All sections of the grid are equally sized and as large as possible.
GridLayout can be set using one of the constructors
Cont..
Cont…

BorderLayout
• The BorderLayout manager divides the window into five areas: East,
South, West, North, and Center.
• At most five components can be added.

• If you want more components, add a Panel, then add components to it.

• Components are added to a BorderLayout by using add(Component,


index) where index is a constant such as
 BorderLayout.EAST
 BorderLayout.SOUTH
 BorderLayout.WEST
 BorderLayout.NORTH
 BorderLayout.CENTER
Step 4. Attach Listeners to your componCont…
 Interacting with a component causes an Event to occur.
 Usually, we click button, move our mouse pointer onto a text, move our mouse pointer onto a
button, enter a text to a text field and etc.
 When a certain action is performed, some event is fired.
 Listeners are associated with control so that it can sense whenever an event is fire
Cont…
• Note that If a component can fire an event, any subclass of the component can fire

the same type of event.

• For example, every GUI component can fire MouseEvent, KeyEvent, FocusEvent,

and ComponentEvent, since Component is the superclass of all GUI components.

• Some of the packages of JDK API that we use in handling event-driven tasks

include:
 java.awt.event.ActionEvent

 java.awt.event.ActionListener

 java.awt.event.MouseEvent

 java.awt.event.MouseListener

 java.awt.event.WindowEvent

 java.awt.event.WindowListene
Listeners, registrations, and handling of events
• Delegation-based model for event handling is employed where a source

object fires an event, and an object interested in the event (a

listener)handles the event.

• For an object to be a listener for an event on a source object, two things

are needed.

• Firstly, the listener object must be an instance of the corresponding

event-listener interface to ensure that the listener has the correct

method for processing the event. Java provides a listener interface for

every type of event.

• The listener interface is usually named XListener for XEvent, with the

exception of MouseMotionListener.
Cont…
• For example, the corresponding listener interface for ActionEvent is

ActionListener and each listener for ActionEvent should implement the

ActionListener interface.

• Secondly, the listener object must be registered by the source object.

• Registration methods depend on the event type. For ActionEvent, the

method is addActionListener.

• In general, the method is named addXListener for XEvent. A source

object may fire several types of events.

• It maintains, for each event, a list of registered listeners and notifies

them by invoking the handler of the listener object to respond to the

event
Cont…
• Example: Assume I have window/frame that has a label named “Name”

and a text field to enter name.

• There is also a button of which text is “show me my input in dialog box”.

• Once we enter a name in the text field, we can click the button to get a

dialog box that contain the name we entered in the text field.

• How can we implement this scenario? Solution: There could be different

solutions.

• But, let us see one way of setting the layout. First, let us create the

necessary containers and components with appropriate layout; then, we

will add the components/containers to the appropriate containers. Here we

go
Cont…
import java.awt.GridLayout; import javax.swing.*; panel1.add(txt_field_name);

public class Example1 extends JFrame{ //let us add the panel and the button to the frame

JLabel label_name; after set the layout of the frame

JTextField txt_field_name; this.setLayout(new GridLayout(2,1));

JButton btn_show; this.add(panel1);

Example1(){ this.add(btn_show);

label_name= new JLabel(“Name:”); //let us set the size, location and set default close

txt_field_name = new JTextField(); aspects of the frame and make the window

btn_show = new JButton(“show me my input in dialog //visible

box”); this.setSize(400,250);

//I want to create a JPanel that could contain the label of this.setLocation(150,200);

the name and the text field of the this.setDefaultCloseOperation(JFrame.EXIT_ON_CLO

//name and, then, I will add this JPanel instance to the SE);

JFrame this.setVisible(true); }

JPanel panel1 = new JPanel(); public static void main(String [] args){ new

panel1.setLayout(new GridLayout(1,2)); Example1(); } }

panel1.add(label_name);
GUI Example in netbean

1. creating new project in netbean


 Go to new=>new project
 type project name(e.g myGUIFoprm)
 uncheck create main class check box
 click on finish
Cont…
2.Add JFrameForm in your project
• right click on your project=>New=>Select JFrameForm

• Type the class name(eg Number)Finish


Cont…
• After clicking Finish button you will see the following GUI
Cont…
3. Add textfields,Labels and buttons in the FrameForm by dragging and dropping
Cont…
4. Changing the properties of Form Components(Name, Text of components)
example change the name of components

Example

jTextField1=>Num1

jTextField2=>Num2

jTextField3=>result

jButton1=>Add

jButton2=>Exit

steps to change name and text

 Right click on a particular component from the navigator window

 select Change text to change display text(jTexTfield1 to " ")

or select Change Variable name(to change name) eg. jTextFiled1 to Num1

 Click on Ok button

N.b. Do the above steps for all componenets


Cont…
Cont…

• You can change different properties of these


components(eg. Foreground color of Labels)
select your component in FrameForm(eg.
Number1 Laabel)
Go to Properties window(right pane)
Select Foreground from the properties=>select
color and click on ok
Cont…
Cont…
• After changing different properties you will get the following interface
Cont…
5. Add Java codes
A. Double click on Exit button and add this code
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
Num1.setText("");
Num2.setText("");
result.setText("");
}
B. Double click on Add button and add the following code
private void addActionPerformed(java.awt.event.ActionEvent evt) {
double r=0.0;
double n1,n2;
//getting content of textfields and convert into numeric value
n1=Double.parseDouble(Num1.getText());
n2=Double.parseDouble(Num2.getText());
r=n1+n2;
//displaying some content on textfields
result.setText(String.valueOf(r));
}
Cont…
The entire code for adding two number from two n2=Double.parseDouble(Num2.getText());
text box and displaying the resul on result text r=n1+n2;
box is the following. //displaying some content on textfields
public class number extends javax.swing.JFrame { result.setText(String.valueOf(r)); }
public number() { public static void main(String args[]) {
initComponents(); } java.awt.EventQueue.invokeLater(new
private void Runnable() {
Num1ActionPerformed(java.awt.event.ActionEv public void run() {
ent evt) {
new number().setVisible(true);
// TODO add your handling code here: }
} }); }
private void
// Variables declaration - do not modify
exitActionPerformed(java.awt.event.ActionEven
t evt) { private javax.swing.JTextField Num1;
Num1.setText(""); private javax.swing.JTextField Num2;
Num2.setText(""); private javax.swing.JButton add;
result.setText(""); } private javax.swing.JButton exit;
private void private javax.swing.JLabel jLabel1;
addActionPerformed(java.awt.event.ActionEven private javax.swing.JLabel jLabel2;
t evt) { private javax.swing.JLabel jLabel3;
double r=0.0; private javax.swing.JTextField result;
double n1,n2; // End of variables declaration
//getting content of textfields }
n1=Double.parseDouble(Num1.getText());
Cont…
6. Compile and Run
When you run the above program,enter values in two number fields and click on Add button ,you
will get an output as follows
Connecting java program to Database
• For connecting java application with the mysql database, you need to follow 5 steps to
perform database connectivity
• In this example we are using MySql as the database. So we need to know following
information for the mysql database:

 Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

 Connection URL: The connection URL for the mysql database

is jdbc:mysql://localhost/javadb where jdbc is the API, mysql is the database, localhost is

the server name on which mysql is running, we may also use IP address, 3306 is the port

number and Javadb is the database name that you created on wamp or other server. you may

use any database, in such case, you need to replace the javadb with your database name.

 Username: The default username for the mysql database is root.

 Password: Password is given by the user at the time of installing the mysql database. In this

example, password is empty


Defining Database Drivers

• Database vendors, such as Microsoft® and Oracle®, implement their database systems

using technologies that vary depending on customer needs, market demands, and

other factors.

• Software applications written in popular programming languages, such as C, C++,

and Java®, need a way to communicate with these databases.

• Open Database Connectivity (ODBC) and Java Database Connectivity (JDBC)

are standards for drivers that enable programmers to write database-agnostic software

applications.

• ODBC and JDBC provide a set of rules recommended for efficient communication

with a database.

• The database vendor is responsible for implementing and providing drivers that

follow these rules.


Deciding Between ODBC and JDBC Drivers
• ODBC is a standard Microsoft Windows® interface that enables
communication between database management systems and applications
typically written in C or C++.

• JDBC is a standard interface that enables communication between database


management systems and applications written in Oracle Java.

• Database Toolbox has a C++ library that connects natively to an ODBC driver.

• Database Toolbox has a Java library that connects directly to a pure JDBC
driver.

• Depending on your environment and what you want to accomplish, decide


whether using an ODBC driver or a JDBC driver meets your needs.
Cont…

 Use native ODBC for:


 Fastest performance for data imports and exports

 Memory-intensive data imports and exports

 All functionality except the runstored procedure function

 Use JDBC for:


 Platform independence, allowing you to work with any

operating system (including Mac and Linux®), driver version,


or bitness
 Access to all Database Toolbox functions
Cont…
• Let's first create a table student in javadb database, but before
creating table, we need to create database first.

1. CREATING DATA BASE AND TABLE IN WAMP

Open WAMP/XAMPP

click con start->type wamp/xampp on run=>click on start


wamp/xampp

Start your MYSQL server from XAMPP/WAMP

Click on PhpMyadmin
Cont…
Cont…
Click on database->type databasename(eg
javadb)
Click on Create
Cont…
 create your table
 Select your database(eg. javadb)

 Type table name and number of fields in the given


boxes

eg Table name:student

number of fields:6

 Click on create
Cont…
 type the column names and select the type for each field as follows
 Then click con Sava
Cont…
2. Connecting to MYSql Database

A. Adding database connectors and drivers into your project


 To connect java application with the mysql database
mysqlconnector.jar file is required to be loaded.
download the jar file mysql-connector.jar
 Load the jar file into your project
 Open netbean=>go to your project(eg javadatabase)

 right click on libraries from your project

 Click con Add JAR/Folder


Cont…
Cont…
select your mysql-connector jar file from your location(eg Desktop),click on open
Cont…
• After it is correctly loaded you will see your mysql-connector
under library in your project as follows
Cont…
 Then Add connection driver into your project
 right click on libraries from your project
 select Add Libraries->From Add Library window select MYSQL JDBC driver and click Add library
button


Cont…
3. Creating Java Interface ,create the following Interface
Cont…
Click on Next button from your Design window and add the following to go
to Next record
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
try{
if(rs.next()){
String fn=txtFname.getText().toString();
String mn=txtMname.getText().toString();
}
else {
rs.previous();
JOptionPane.showMessageDialog(Student.this, "End of File");
}}
catch(SQLException err){
JOptionPane.showMessageDialog(Student.this, err.getMessage());
}}
• To make the ResultSet type allow us to scroll

backwards as well as forwards use the following


during database connection for the resultSet variable

stmt =
con.createStatement( ResultSet.TYPE_SCROLL
_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE );
Cont…

Move Back through a Java Database

• The code for the Previous button is similar to theNext button. But instead

of using rs.Next, you use rs.Previous.

• Return to the Design window and double click your Previous button to

create a code stub.

• Instead of typing out all that code again, simply copy and paste the

code from your Next button. Then change the rs.Next, in the IF

statement to rs.Previous. Change the rs.Previous in the ELSE part to

rs.Next. You can also change your error message text from "End of

File" to "Start of File".


Cont…

Updating a Record
• The ResultSet has Update methods that allow you to update records not only in the ResultSet itself, but in the
underlying database. Let's see how it works.

• Make your form a bit longer. Now add a new panel to the form. Add

a new button to the panel.

• Change the default variable name to btnUpdateRecord.

• Change the text on the button to Update Record.

• We're also going to have buttons to create a new record in the

database, to save a record, cancel any updates, and to delete a record.

• So add four more buttons to the panel. Make the following changes:
Cont…

• Button Variable Name: btnNewRecord


Button Text: New Record

• Button Variable Name: btnDeleteRecord


Button Text: Delete Record

• Button Variable Name: btnSaveRecord


Button Text: Save New Record

• Button Variable Name: btnCancelNewRecord


Button Text: Cancel New Record

• When you're done, your form should look something like this one
(though feel free to rearrange the buttons):
Cont…

• Double click your Update button to create a code stub.

• The first thing to do is get the text from the Text Fields:

String first = textFirstName.getText( );

String last = textLastName.getText( );

String job = textJobTitle.getText( );

String ID = textID.getText( );

• If we want to update an ID field, however, we need to convert the String to an Integer:

intnewID = Integer.parseInt( ID );

• The Integer object has a method called parseInt. In between the round brackets of parseInt, you

type the string that you're trying to convert.

• Now that we have all the data from the Text Fields, we can call the relevant update methods of the

ResultSet object:

rs.updateString( "First_Name", first );


Cont…

• There are quite a few different update methods to choose from. The one above uses

updateString. But you need the field type from your database table here. We have

three strings (First_Name, Last_Name, Job_Title) and one integer value (ID). So

we need three updateStringmethods and one updateInt.

• In between the round brackets of the update methods, you need the name of a

column from your database (though this can be its Index value instead). After a

comma you type the replacement data. So, in the example above, we want to

update the First_Name column and replace it with the value held in the variable

called first.

• The update methods just update the ResultSet, however. To commit the changes to

the database, you issue an updateRow command:

• rs.updateRow( );
Cont…

• Here are all the lines of code to update the ResultSet and the database table:

try {
rs.updateInt( "Id", idno );
rs.updateString( “fname", firstname );
rs.updateString( “mname", middlename );

rs.updateRow( );
JOptionPane.showMessageDialog(Student.this, "Updated");
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
Cont…
4. Add the following sample java code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class db extends javax.swing.JFrame {
//creating connection,statement and result variable
Connection con;
Statement stmt;
ResultSet rs;
public db() {
initComponents();
Doconnect();
}
Cont…
//function to connect to database String Mn=rs.getString("Mname");
public void Doconnect() String dept=rs.getString("Department");
{ String sex=rs.getString("Sex");
try{ int year=rs.getInt("Year");
String host="jdbc:mysql://localhost/javadb" ; String y=Integer.toString(year);
//creating connection variables //displaying the first records in the text fields
String usern="root"; ID.setText(id);
String pass=""; Fname.setText(Fn);
Mname.setText(Mn);
con=DriverManager.getConnection(host,usern,pass Department.setText(dept);
); //connecting to Mysql database
Sex.setText(sex);
stmt=con.createStatement();
Year.setText(y);
String sql="SELECT * FROM student";//select
records from student table
}
rs=stmt.executeQuery(sql);
catch(SQLException err){
rs.next(); //move cursor to the first record and get
date JOptionPane.showMessageDialog(this,
err.getMessage());
String id=rs.getString("ID");
}}
//getting data from database and store on variables
String Fn=rs.getString("Fname");//read from the
Fname field and store on Fn variable
Cont…
private javax.swing.JButton ADD; private javax.swing.JLabel jLabel5;
private javax.swing.JTextField Department; private javax.swing.JLabel jLabel6;
private javax.swing.JButton First; // End of variables declaration
private javax.swing.JTextField Fname; }
private javax.swing.JTextField ID;
private javax.swing.JButton Last;
private javax.swing.JTextField Mname;
private javax.swing.JButton Next;
private javax.swing.JButton Previous;
private javax.swing.JTextField Sex;
private javax.swing.JButton Show;
private javax.swing.JTextField Year;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
Cont…
• Run your project and yow will see the following
Servlets
• Servlet technology is used to create a web application (resides at
server side and generates a dynamic web page).

• Servlet technology is robust and scalable because of java


language. Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side programming
language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.

• There are many interfaces and classes in the Servlet API such as
Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse, etc.
Cont…
• Servlet is a technology which is used to create a web application.

• Servlet is an API that provides many interfaces and classes


including documentation.
• Servlet is an interface that must be implemented for creating any
Servlet.
• Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any
requests.
• Servlet is a web component that is deployed on the server to
create a dynamic web page.
Cont…
What is a web application?

• A web application is an application accessible


from the web.
• A web application is composed of web
components like Servlet, JSP, Filter, etc. and other
elements such as HTML, CSS, and JavaScript.
• The web components typically execute in Web
Server and respond to the HTTP request.
CGI (Common Gateway Interface)

• CGI technology enables the web server to call an external


program and pass HTTP request information to the external
program to process the request. For each request, it starts a
new process.
Cont…

• Disadvantages of CGI
 There are many problems in CGI technology:

 If the number of clients increases, it takes more time for sending the response.

 For each request, it starts a process, and the web server is limited to start processes.

 It uses platform dependent language e.g. C, C++, perl.

• Advantages of Servlet
 Better performance: because it creates a thread for each request, not process.

 Portability: because it uses Java language.

 Robust: JVM manages Servlets, so we don't need to worry about the memory

leak, garbage collection, etc.

 Secure: because it uses java language.


Cont…

• Disadvantages of CGI
 There are many problems in CGI technology:

 If the number of clients increases, it takes more time for sending the response.

 For each request, it starts a process, and the web server is limited to start processes.

 It uses platform dependent language e.g. C, C++, perl.

• Advantages of Servlet
 Better performance: because it creates a thread for each request, not process.

 Portability: because it uses Java language.

 Robust: JVM manages Servlets, so we don't need to worry about the memory

leak, garbage collection, etc.

 Secure: because it uses java language.


Creating a servlet in NetBeans IDE:

• Step 1 Open Netbean


• Step 2 Click on file then New Project
You will get the following
Cont…
• Step 3:- Select Java Web(from categories Section)-> select
Web application(from Project Section)
• Step 4:-Click on Next->Type Project Name->Click On next-
>Select Server from Server dropdown box(Example GlassFish
Server v 4.1.1
Cont…
Click on Finish
Step 4:- Goto your project in the project explorer->click on
source package->right click on it>new->servlet
Cont…
• Type your servlet Name(Eg Student)
Cont…
• Click on Next->Finish * @throws IOException if an I/O error occurs
import java.io.IOException; */
import java.io.PrintWriter; protected void processRequest(HttpServletRequest
import javax.servlet.ServletException; request, HttpServletResponse response)
import javax.servlet.annotation.WebServlet; throws ServletException, IOException {
import javax.servlet.http.HttpServlet; response.setContentType("text/html;charset=UTF-
import javax.servlet.http.HttpServletRequest; 8");
import javax.servlet.http.HttpServletResponse; try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use
following sample code. */
/**
out.println("<!DOCTYPE html>");
*
out.println("<html>");
* @author Meki
out.println("<head>");
*/
out.println("<title>Servlet Student</title>");
@WebServlet(urlPatterns = {"/Student"})
public class Student extends HttpServlet {
out.println("</head>");
out.println("<body>");
/**
out.println("<h1>Servlet Student at " +
* Processes requests for both HTTP request.getContextPath() + "</h1>");
<code>GET</code> and <code>POST</code>
out.println("</body>");
* methods.
out.println("</html>");
*
}
* @param request servlet request
}
* @param response servlet response
* @throws ServletException if a servlet-specific error
occurs
Cont…
• To create HTML file in your project
=> Goto your web project =>Right Click on
it=>New=>HTML=>
Cont…

• Type Your HTML page name(eg Student)=>Finish then


you will get the following
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
</body>
handle HTML form data with Java Servlet
• In this section, you will see how to read values of common input

fields from HTML form on the server side with Java servlet

• You know, handling form data represented in HTML page is a very

common task in web development.

• A typical scenario is the user fills in fields of a form and submits it.

• The server will process the request based on the submitted data, and

send response back to the client.

• The following picture depicts that workflow with Java servlet on the

server side:
Cont..
Cont..
•To create a form in HTML we need to use the following
tags:
 <form>: to create a form to add fields in its body.
 <input>, <select>, <textarea>…: to create form fields like text boxes,
dropdown list, text area, check boxes, radio buttons,… and submit button.

• To make the form works with Java servlet, we need to


specify the following attributes for the <form> tag:
 method=”post”: to send the form data as an HTTP POST request to the server.
Generally, form submission should be done in HTTP POST method.
 action=”URL of the servlet”: specifies relative URL of the servlet which is
responsible for handling data posted from this form.
Cont..
• For example, following is HTML code of a login form:
<form name="loginForm" method="post" action="loginServlet">
Username: <input type="text" name="username"/> <br/>
Password: <input type="password"
name="password"/> <br/>
<input type="submit" value="Login" />
</form>
Cont..
• On the server side, we need to create a Java servlet which is
mapped to the URL: loginServlet, as specified in the form’s
action attribute. Following is code of the servlet:
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
// code to process the form...
}
}
Cont..
• Notice that the servlet’s URL is specified by the @WebServlet annotation before

the servlet class.


• When the user submits the login form above, the servlet’s doPost() method will

be invoked by the servlet container.


• Typically we will do the following tasks inside doPost() method:

– Read values of the fields posted from the form via the request object

(implementation of javax.servlet.http.HttpServletRequest interface).


– Do some processing, e.g. connecting to database to validate the

username and password.


– Return response back to the user via the respone object

(implementation
Cont..
• To read values of form’s fields, the HttpServletRequest interface provides the
following methods:
• String getParameter(String name): gets value of a field which is specified by
the given name, as a String. The method returns null if there is no form field
exists with the given name.
• String[] getParameterValues(String name): gets values of a group of fields
which have same name, in an array of String objects. The method returns null if
there is no field exists with the given name.
• Note that the above methods can also deal with parameters in URL’s query
string, hence the name getParameter.
• For example, we can write the following code in the doPost() method to read
values of form’s fields:
Cont..
String username = request.getParameter("username");
String password = request.getParameter("password");

•To send response back to the client, we need to obtain a writer from
the response object by calling the method getWriter() of
the HttpServletResponse interface:
PrintWriter writer = response.getWriter();

• Then use the print() or println() method to deliver the response (in
form of HTML code). For example:
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "</h2>";
htmlRespone += "</html>";
writer.println(htmlRespone);
Cont..
request.getParameter("username");
Here’s complete code of the servlet class to
String password =
process the login form: request.getParameter("password");
import java.io.IOException; System.out.println("username: " +
import java.io.PrintWriter; username);
System.out.println("password: " +
import javax.servlet.ServletException;
password);
import javax.servlet.annotation.WebServlet; // do some processing here...
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; // get response writer
PrintWriter writer = response.getWriter();
import javax.servlet.http.HttpServletResponse;
@WebServlet("/loginServlet") // build HTML code
String htmlRespone = "<html>";
public class LoginServlet extends HttpServlet
htmlRespone += "<h2>Your username is:
{
" + username + "<br/>";
protected void doPost(HttpServletRequest
request, htmlRespone += "Your password is: " +
password + "</h2>";
HttpServletResponse response) throws
htmlRespone += "</html>";
ServletException, IOException {
// return response
// read form fields
String username = writer.println(htmlRespone); }}
Cont..
• So far you have got the ins and outs when handling HTML form data with Java
servlet.
• For your reference, we provide a list of examples for handling common HTML
form fields as below. Note that we use the System.out.println() statement in
servlet to see the output.
 Read values of text field and password field
• HTML code:
Username: <input type="text" name="username"/>
Password: <input type="password" name="password"/>
Cont..
• Java code in servlet:
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username is: " + username);
System.out.println("password is: " + password);

 Read value of checkbox field


• HTML code:
Speaking language:
<input type="checkbox" name="language" value="english" />English
<input type="checkbox" name="language" value="french" />French
• Java code in servlet
String languages[] = request.getParameterValues("language");
if (languages != null) {
System.out.println("Languages are: ");
for (String lang : languages) {
System.out.println("\t" + lang);
Cont..
• Read value of radio button field
• HTML code:
Gender:
<input type="radio" name="gender" value="male" />Male
<input type="radio" name="gender" value="female" />Female
• Java code in servlet
String gender = request.getParameter("gender");
System.out.println("Gender is: " + gender);
• Read value of dropdown list (combobox) field
• HTML code
Category:
<select name="jobCat">
<option value="tech">Technology</option>
<option value="admin">Administration</option>
<option value="biology">Biology</option>
<option value="science">Science</option>
Cont..
Java code in servlet:
String jobCategory = request.getParameter("jobCat");
System.out.println("Job category is: " + jobCategory);

• Read data of file upload field

To create a form to upload file, we need to specify the enctypeattribute for


the <form> tag as follow:
<form method="post" action="uploadServlet" enctype="multipart/form-data">
Select file to upload: <input type="file" name="uploadFile" />
<input type="submit" value="Upload" />
</form>
Manipulate XAMPP Mysql database using Servlet
Step 1: Create Web project.
=> Go to file->new project->select java web from categories and Web
application from project Section
Cont…
• Click on next->Type project
name(MyServletDB)->Next->Finish
Cont…
Step2: Add Mysql Connector and add JDBC driver to your
project(MyServletDb)
 To add Mysql-connector(assum you have downloaded and
store somewhere in your PC drive otherwise download it )
-> right click on libraries under your project(MyServletDb)
Cont…
• Select your Mysql-connector-java-8.1.1
(depend on your connector version)->click on
Open
Cont…
• Once you properly add your mysql-connector-
java file in to your project you will see the
following under libraries
Cont…
Adding JDBC driver into your project
=>right click on libraries->add library->select MYSQL JDBC
Driver from the available drivers dialog box
Cont…
• Step 3: Create a database and Table using XAMPP/WAMP. Assume
Database javadb and table student (student table)
Cont…
Step 4: Create a HTML registration Form
=> Right click on your project(MyServletDb)->new->select
HTML->
Cont…
->Type page name(eg Registration)->Click on
Finish
Cont…
• ->add the following HTML code <td>Date of Birth</td>
<td><input type="date" name="userDOB" required/></td>
<!doctype html>
</tr>
<body>
<tr>
<form action="./InsertData" method="post">
<td>Gender</td>
<fieldset style="width:20%; background-color:#ccffeb">
<td><input type="radio" name="gender"
<h2 align="center">Registration form</h2><hr>
value="male" checked> Male
<table>
<input type="radio" name="gender" value="female">
<tr> Female </td></tr>
<td>First Name</td> <tr>
<td><input type="text" name="fname" required /></td> <td>Country</td>
</tr> <td><select name="userCountry"
<tr> style="width:130px">
<td>Middle Name </td> <option>Select a country</option>
<td><input type="text" name="mname" required /></td> <option>India</option>
</tr> <option>America</option>
<tr> <option>England</option>
<td>Last Name</td> <option>other</option></select>
<td><input type="text" name="lname" required </td>
/></td> </tr>
</tr> <tr>
<tr> <td><input type="reset" value="Reset"/></td>
<td>Department</td> <td><input type="submit" value="Register"/></td>
<td><input type="text" name="department" </tr>
required/></td>
</table> </fieldset> </form></body> </html>
</tr>
<tr>
Cont…
• When you run Registration.html file you will
get the following
Cont…

Step 5: Create Servlet to connect to MYSQL database


and insert record into Student Table from Registration
form
 Right click on your project=>new=>select servlet
Cont…

Type servlet page name(eg InsertData)Click


NextFinish
Then under the source package in your project you will
see the created servlet file(InsertData.java)
Cont…

• Add the following code in your InsertData.java


import java.io.*;
import java.lang.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/InsertData")//for web url
public class InsertData extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/javadb";
Connection connection;
Cont…
try{
//read value from form
String fn=request.getParameter("fname");
String mn=request.getParameter("mname");
String ln=request.getParameter(“lname");
String dept=request.getParameter(“department");
String gender=request.getParameter(“gender");
String dateofb=request.getParameter(“dateofb");
String country=request.getParameter(“country");
Class.forName("com.mysql.jdbc.Driver");//handl driver type
connection = DriverManager.getConnection (connectionURL, "root", "");//create connection
//perform insert operation into students table
PreparedStatement pst = connection.prepareStatement
("insert into student(fname,mname,lname,department,dateofb,gender,country) values(?,?,?,?,?,?,?)");
pst.setString(1,fn);
pst.setString(2,mn);
pst.setString(3,ln);
pst.setString(4,dept);
pst.setString(5,dateofb);
pst.setString(6,gender);
pst.setString(7,country);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else{
pw.println("failed to insert the data");
}} }
catch (Exception e){
pw.println(e);
Cont…

• Fill and select all values and click on Register


Button as follows
Cont…
• When you click register button you will see
the following

• Open your student table, then you can see as


follows
Update records in servlet from HTML form

• To update record do the following


Create data base connection
String connectionURL =
"jdbc:mysql://localhost/javadb";
Connection connection;
Class.forName("com.mysql.jdbc.Driver");
//creating connection by host name,username and
password
connection = DriverManager.getConnection
(connectionURL, "root", "");
Cont…

• Get form value


String idno=request.getParameter("idno");
int id=Integer.valueOf(idno);
String fn=request.getParameter("fname");
String mn=request.getParameter("mname");
String ln=request.getParameter("lname");
String dept=request.getParameter("department");
String gender=request.getParameter("gender");
String dateofb=request.getParameter("dateofb");
String country=request.getParameter("country");
Cont…
• Update your table
PreparedStatement ps =
connection.prepareStatement("UPDATE student SET
fname=?, mname=?,lname=?,department=?,dateofbirth=?,
gender=?,country=? WHERE Id=?");
ps.setString(1,fn);
ps.setString(2, mn);
ps.setString(3, ln);
ps.setString(4, dept);
ps.setString(5, dateofb);
ps.setString(6, gender);
ps.setString(7, country);
ps.setInt(8,id);
Search Record

• Create the following search Form(serach.html)

<!DOCTYPE html>
<html>
<body>
<form action="./Search" method="get">
Enter ID:<input type="text" name="idno"><br>
<input type="submit" value="search">
</form>
</body>
</html>
Cont…
• Create a servlet file (Search.java) and add the following
code ResultSet rs=ps.executeQuery();
import java.io.*;
import java.sql.*; /* Printing column names */
import javax.servlet.ServletException; ResultSetMetaData rsmd=rs.getMetaData();
import javax.servlet.annotation.WebServlet; int total=rsmd.getColumnCount();
import javax.servlet.http.*; out.print("<tr>");
@WebServlet("/Search") for(int i=1;i<=total;i++)
public class Search extends HttpServlet { {
out.print("<th>"+rsmd.getColumnName(i)+"</th>");
public void doGet(HttpServletRequest request, }
HttpServletResponse response)
throws ServletException, IOException { out.print("</tr>");

response.setContentType("text/html"); /* Printing result */


PrintWriter out = response.getWriter();
while(rs.next())
String idno=request.getParameter("idno"); {
int id=Integer.valueOf(idno); out.print("<tr><td>"+rs.getInt(1)+"</
try{ td><td>"+rs.getString(2)+"
Class.forName("com.mysql.jdbc.Driver"); </td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+
String connectionURL = "jdbc:mysql://localhost/javadb"; "</td></tr>");
Connection con;
con=DriverManager.getConnection }
(connectionURL, "root", "");
PreparedStatement ps=con.prepareStatement("select * from out.print("</table>");
student where Id=?");
ps.setInt(1,id); }catch (Exception e2) {e2.printStackTrace();}

out.print("<table width=50% border=1>"); finally{out.close();} } }


Cont…

• Run search.html then enter Id number and


click on Search button . You will get the
following out put
Display Data From Database Through Servlet And JDBC

You might also like