Chapter 6 GUI and JDBC
Chapter 6 GUI and JDBC
– Overview of GUI
– Concepts of GUI
AWT
Swings
– Overview of JDBC
– Java Servlets
GUI: Graphical User Interface
application, so that they can learn it more quickly and use it more
productively.
• 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.
• 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
of user.
They are generated as consequences of a person interacting with the graphical
through keyboard, selecting an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user
• 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...
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.
These Listener interfaces forecast some public abstract callback methods which
If you do not implement the any if the predefined interfaces then your class can
• These are the methods that are provided by API provider and are defined by the
can be "called back" (i.e., invoked) later—usually when a specific event occurs or
a task completes.
• If a component wants some listener will listen to it's events the source must register
button.addActionListener(new ActionListener() {
System.out.println("Button clicked");
}});
Event Source
Event Listener
interface.
clicked.
The ActionEvent e object contains details about the event (like the
• ActionEvent
This object (e) is automatically created and passed by the system when
import java.awt.event.*;
//declaring variable
public AwtControlDemo(){
prepareGUI();
}
Cont..
private void prepareGUI(){ statusLabel.setSize(350,100);
mainFrame.setSize(400,400); mainFrame.add(headerLabel);
mainFrame.addWindowListener(new mainFrame.add(statusLabel);
WindowAdapter() { mainFrame.setVisible(true); }
public void windowClosing(WindowEvent
windowEvent){
System.exit(0); } });
headerLabel.setAlignment(Label.CENTER);
tatusLabel.setAlignment(Label.CENTER);
Example
private void showEventMethod(){ cancelButton.setActionCommand("Cancel");
Button"); ButtonClickListener());
Button("Submit"); ButtonClickListener());
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-
• Swing GUI components allow you to specify a uniform look-and-feel for your application
• 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 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 gives far more options for everything (buttons with pictures on them, etc.).
• AWT classes are contained inside package java.awt while Swing classes are
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
data model.
• MVC (Model-View-Controller) is a design pattern that helps organize
StudentView.java
System.out.println("Student: ");
}}
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
JPanel:
JPanel is a region internal to a JFrame or another JPanel.
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”.
The visual arrangement of the components depends on the container's layout (which are part
of helper classes)
Cont…
Choosers
File chooser (JFileChooser)
Color chooser (JColorChooser)
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.
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
import javax.swing.*;
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;
setTitle("First JFrame");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); }
JButton:
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.
not
Here two alternative examples that create a JButton component with text “Click Here”. JButton button= new
OR
JLabel: A label is a display area for a short text(a non-editable), an image, or both.
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.
import java.awt.event.*;
import javax.swing.*;
public class JavaFrame {
frame.setSize(220, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.setLayout(null);
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.
• There are three important swing components for the development of menu
driven application.
constructor 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.
menu/submenu.
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);
• 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.
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);
pane, etc).
• 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
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.
• For example, every GUI component can fire MouseEvent, KeyEvent, FocusEvent,
• 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
are needed.
method for processing the event. Java provides a listener interface for
• 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 interface.
method is addActionListener.
event
Cont…
• Example: Assume I have window/frame that has a label named “Name”
• 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.
solutions.
• But, let us see one way of setting the layout. First, let us create the
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
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
box”); this.setSize(400,250);
//I want to create a JPanel that could contain the label of this.setLocation(150,200);
//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.add(label_name);
GUI Example in netbean
Example
jTextField1=>Num1
jTextField2=>Num2
jTextField3=>result
jButton1=>Add
jButton2=>Exit
Click on Ok button
Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
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.
Password: Password is given by the user at the time of installing the mysql database. In this
• Database vendors, such as Microsoft® and Oracle®, implement their database systems
using technologies that vary depending on customer needs, market demands, and
other factors.
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
• 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.
Open WAMP/XAMPP
Click on PhpMyadmin
Cont…
Cont…
Click on database->type databasename(eg
javadb)
Click on Create
Cont…
create your table
Select your database(eg. javadb)
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
•
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
stmt =
con.createStatement( ResultSet.TYPE_SCROLL
_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE );
Cont…
• The code for the Previous button is similar to theNext button. But instead
• Return to the Design window and double click your Previous button to
• 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
rs.Next. You can also change your error message text from "End of
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
• So add four more buttons to the panel. Make the following changes:
Cont…
• When you're done, your form should look something like this one
(though feel free to rearrange the buttons):
Cont…
• The first thing to do is get the text from the Text Fields:
String ID = textID.getText( );
intnewID = Integer.parseInt( ID );
• The Integer object has a method called parseInt. In between the round brackets of parseInt, you
• Now that we have all the data from the Text Fields, we can call the relevant update methods of the
ResultSet object:
• 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
• 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
• 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).
• 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.
• 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.
• Advantages of Servlet
Better performance: because it creates a thread for each request, not process.
Robust: JVM manages Servlets, so we don't need to worry about the memory
• 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.
• Advantages of Servlet
Better performance: because it creates a thread for each request, not process.
Robust: JVM manages Servlets, so we don't need to worry about the memory
fields from HTML form on the server side with Java servlet
• 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
• 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.
– Read values of the fields posted from the form via the request 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);
<!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>");