Java Unit-3 Lecture-22,23 24 (5 Files Merged)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 147

UNIVERSITY INSTITUTE OF ENGINEERING

DEPARTMENT OF AIT - CSE


Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)

Lecture -22, 23 & 24 DISCOVER . LEARN . EMPOWER


AWT, SWING, LAYOUT
Chapter Course Objectives

● To understand about AWT.


● To understand Type of Swing.
16.
● To understand about Layout.

Chapter Course Outcomes


After completion of this course, student will be able to
● Learn the basic AWT.
16.
● Learn the basic about Swing.
● Different Layout design

2
AWT, SWING, LAYOUT
Java AWT Tutorial
•Java AWT (Abstract Window Toolkit) is an API to develop GUI or
window-based applications in java.

•Java AWT components are platform-dependent i.e. components are


displayed according to the view of operating system.

•AWT is heavyweight i.e. its components are using the resources of OS.

•The java.awt package provides classes for AWT api such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
Cont..
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class
are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It
can have other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It
can have other components like button, textfield etc.
Useful Methods of Component class
Creating Frame
Create a Frame class object:
Frame f= new Frame();

Create a Frame class object and pass its title:


Frame f= new Frame(“My Frame”);

Used Frame to user defined class:


Class MyFrame extends Frame
MyFrame f=new MyFrame();
AWT Example
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
Event Delegation Model
•Changing the state of an object is known as an event. For example, click
on button, dragging mouse etc.
•The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Event Handling Model of AWT

Event object

Event handling
methods

Event source Event listener


Action Events on Buttons

ActionEvent

actionPerformed(..)

Button ActionListener
Steps to perform Event Handling
Following steps are required to perform event handling:
Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
Cont..
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
Java ActionListener Interface
• The Java ActionListener is notified whenever you click on the button or
menu item. It is notified against ActionEvent.
• The ActionListener interface is found in java.awt.event package.
• It has only one method: actionPerformed().

• actionPerformed() method
• The actionPerformed() method is invoked automatically whenever
you click on the registered component.
• public abstract void actionPerformed(ActionEvent e);
Java ActionListener Interface(cont..)
How to write ActionListener
• The common approach is to implement the ActionListener. If you
implement the ActionListener class, you need to follow 3 steps:

1) Implement the ActionListener interface in the class:


• public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
• component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
• public void actionPerformed(ActionEvent e)
•{
• //Write the code here
•}
import java.awt.*;
Ex: import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
static TextField tf ;
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(new ActionListenerExample());
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome You.");
} }
• import java.awt.*;
• import java.awt.event.*;
• //1st step f.add(b);
f.add(tf);
• public class ActionListenerExample implements ActionListener{
f.add(tf1);
• static TextField tf,tf1 ; f.add(l);
• static Label l; f.setSize(400,400);
f.setLayout(null);
• public static void main(String[] args) {
f.setVisible(true);
• Frame f=new Frame("ActionListener Example"); }
• tf=new TextField(); //3rd step
• tf.setBounds(50,50, 150,20); public void actionPerformed(ActionEvent e){
int a = Integer.parseInt(tf.getText());
• tf1=new TextField(); int b = Integer.parseInt(tf1.getText());
• tf1.setBounds(220,50, 150,20); int c = a + b;
• l = new Label(""); l.setText("Their sum is = " + String.valueOf(c));
}
• l.setBounds(100, 120, 85, 20); }
• Button b=new Button("Click Here");
• b.setBounds(50,100,60,30);
• //2nd step
• b.addActionListener(new ActionListenerExample());

18
Java Swing
JAVA Swing
•Java Swing is a part of Java Foundation Classes (JFC) that is used to
create window-based applications.
• It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
•Unlike AWT, Java Swing provides platform-independent and lightweight
components.
•The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Difference between AWT and Swing
Hierarchy of Java Swing classes
Simple Java Swing Example
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Layout
Java LayoutManagers
• The LayoutManagers are used to arrange components in a particular
manner.
• LayoutManager is an interface that is implemented by all the classes
of layout managers.
• There are following classes that represents the layout managers:
 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout
 javax.swing.BoxLayout
 javax.swing.GroupLayout
 javax.swing.ScrollPaneLayout
 javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five
regions: north, south, east, west and center. Each region (area)
may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for
each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER

Constructors of BorderLayout class:


BorderLayout(): creates a border layout but with no gaps
between the components.
BorderLayout(int hgap, int vgap): creates a border layout with
the given horizontal and vertical gaps between the components.
Border Layout Ex:
import java.awt.*; f.add(b1,BorderLayout.NORTH);
import javax.swing.*; f.add(b2,BorderLayout.SOUTH);
public class Border { f.add(b3,BorderLayout.EAST);
JFrame f; f.add(b4,BorderLayout.WEST);
Border(){ f.add(b5,BorderLayout.CENTER);
f=new JFrame(); f.setSize(300,300);
JButton b1=new JButton("NORTH"); f.setVisible(true);
JButton b2=new JButton("SOUTH"); }
JButton b3=new JButton("EAST"); public static void main(String[] args) {
JButton b4=new JButton("WEST"); new Border();
JButton b5=new JButton("CENTER"); } }
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class:
GridLayout(): creates a grid layout with one column per component in a
row.
GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns alongwith given horizontal and vertical
gaps.
Grid Layout Ex:
import java.awt.*; f.add(b1);

import javax.swing.*; f.add(b2);

public class MyGridLayout{ f.add(b3);

JFrame f; f.add(b4);

MyGridLayout(){ f.add(b5);

f=new JFrame(); f.add(b6);

JButton b1=new JButton("1"); f.add(b7);

JButton b2=new JButton("2"); f.add(b8);

JButton b3=new JButton("3"); f.add(b9);

JButton b4=new JButton("4");


JButton b5=new JButton("5"); f.setLayout(new GridLayout(3,3));

JButton b6=new JButton("6"); //setting grid layout of 3 rows and 3 columns

JButton b7=new JButton("7"); f.setSize(300,300);

JButton b8=new JButton("8"); f.setVisible(true);

JButton b9=new JButton("9"); }


public static void main(String[] args) {
new MyGridLayout();
} }
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Constructors of FlowLayout class
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Java FlowLayout Ex:
f.add(b1);
import java.awt.*;
f.add(b2);
import javax.swing.*; f.add(b3);
f.add(b4);
public class MyFlowLayout{ f.add(b5);
JFrame f;
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
MyFlowLayout(){
f=new JFrame(); //setting flow layout of right alignment

f.setSize(300,300);
JButton b1=new JButton("1"); f.setVisible(true);
JButton b2=new JButton("2"); }
JButton b3=new JButton("3"); public static void main(String[] args) {
JButton b4=new JButton("4"); new MyFlowLayout();
}
JButton b5=new JButton("5");
}
Summary
. Discussed about AWT.
. Discussed about Swing components and container.
. Discussed different layouts.

32
Home Work
Q1. Difference between Applet and Swing?

Q2.Difference between Container and Components?

33
References

Online Video Link


• https://nptel.ac.in/courses/106/105/106105191/
• https://www.coursera.org/courses?query=java
• https://www.coursera.org/specializations/object-oriented-programming
• https://www.youtube.com/watch?v=aqHhpahguVY

Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .

34
THANK YOU

For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)

Lecture -25 DISCOVER . LEARN . EMPOWER


Java Beans
Chapter Course Objectives

● To understand about Java Beans.


17. ● To understand getter and setter methods.

Chapter Course Outcomes


After completion of this course, student will be able to
● Learn the basic about Java Beans.
17.
● Learn about getter and setter methods

2
JavaBean
JAVA Beans
A JavaBean is a Java class that should follow the following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and setter
methods.
Why use JavaBean?
• According to Java white paper, it is a reusable software component.
• A bean encapsulates many objects into one object so that we can access
this object from multiple places. Moreover, it provides easy
maintenance.

public class Employee implements Serializable


{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
How to access the JavaBean class?
• To access the JavaBean class, we should use getter and setter methods.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

6
JavaBean Properties
• A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.
• A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.

2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
7
Advantages of JavaBean
The following are the advantages of JavaBean:/p>
• The JavaBean properties and methods can be exposed to another application.
• It provides an easiness to reuse the software components.

Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
• JavaBeans are mutable. So, it can't take advantages of immutable objects.
• Creating the setter and getter method for each property separately may lead to the
boilerplate code.

8
Summary
. Discussed about Java Beans.

. Discussed about getter and setter methods.

9
Home Work
Q1. Difference between Java Bean and Bean?

Q2. What is a Bean? Why is not a Bean an Applet?

10
References

Online Video Link


• https://nptel.ac.in/courses/106/105/106105191/
• https://www.coursera.org/courses?query=java
• https://www.coursera.org/specializations/object-oriented-programming
• https://www.youtube.com/watch?v=aqHhpahguVY

Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .

11
THANK YOU

For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)

Lecture -26, 27 &28 DISCOVER . LEARN . EMPOWER


JAVA SERVLET
Chapter Course Objectives

● To understand about Java Servlet.


● To understand about Servlet Life Cycle.
18.
● To understand about Http request and response.

Chapter Course Outcomes


After completion of this course, student will be able to
● Learn the basic about Java Servlet.
18.
● Servlet Life Cycle.
● Learn about Http request and response.

2
JAVA SERVLET
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.

• There are many interfaces and classes in the Servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse, etc.
What is a Servlet?
• 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.
CGI vs Servlet
7
Static website Vs Dynamic website
9
HTTP (Hyper Text Transfer Protocol)

• The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative, distributed,
hypermedia information systems. It is the data communication protocol used to establish
communication between client and server
HTTP Requests

HTTP Request Description

GET Asks to get the resource at the requested


URL.
POST Asks the server to accept the body info
attached. It is like GET request with extra info
sent with the request.

HEAD Asks for only the header part of whatever a


GET would return. Just like GET but with no
body.
TRACE Asks for the loopback of the request message,
for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at


the requested URL.
DELETE Says to delete the resource at the requested
URL.
OPTIONS Asks for a list of the HTTP methods to which
the thing at the request URL can respond
Get vs. Post
GET POST
1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data is data can be sent because data is sent in body.
sent in header.

2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means Post request is non-idempotent.


second request will be ignored until response
of first request is delivered

5) Get request is more efficient and used Post request is less efficient and used less
more than Post. than get.
Servlet Container
• It provides the runtime environment for JavaEE (j2ee) applications. The
client/user can request only a static WebPages from the server. If the
user wants to read the web pages as per input then the servlet container
is used in java.
• The servlet container is the part of web server which can be run in a
separate process.
Servlet API

• The javax.servlet and javax.servlet.http packages represent interfaces and classes


for servlet api.

• The javax.servlet package contains many interfaces and classes that are used by
the servlet or web container. These are not specific to any protocol.

• The javax.servlet.http package contains interfaces and classes that are


responsible for http requests only.
Servlet Interface
• Servlet interface provides common behavior to all the servlets.
• Servlet interface defines methods that all servlets must implement.

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.

public void service(ServletRequest provides response for the incoming request. It


request,ServletResponse response) is invoked at each request by the web
container.

public void destroy() is invoked only once and indicates that servlet
is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as


writer, copyright, version etc.
GenericServlet class
• GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service
method.
• GenericServlet class can handle any type of request so it is protocol-independent.

Methods of GenericServlet class


•public void init(ServletConfig config) is used to initialize the servlet.
•public abstract void service(ServletRequest request, ServletResponse response) provides service
for the incoming request. It is invoked at each time when user requests for a servlet.
•public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being
destroyed.
•public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
•public void init() it is a convenient method for the servlet programmers, now there is no need to call
super.init(config)
•public String getServletName() returns the name of the servlet object.
HttpServlet class
• HttpServlet is an abstract class given under the servlet-api present.

• It is present in javax.servlet.http package and has no abstract methods. It


extends GenericServlet class.

• When the servlet container uses HTTP protocol to send request, then it
creates HttpServletRequest and HttpServletResponse objects.
HttpServletRequest binds the request information like header and
request methods and HttpServletResponse binds all information of HTTP
protocol.
HttpServlet class Methods
• public void service(ServletRequest req,ServletResponse res) dispatches
the request to the protected service method by converting the request
and response object into http type.
• protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the
request to the do____() method depending on the incoming http
request type.
• protected void doGet(HttpServletRequest req, HttpServletResponse
res) handles the GET request. It is invoked by the web container.
• protected void doPost(HttpServletRequest req, HttpServletResponse
res) handles the POST request. It is invoked by the web container.
• protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
HttpServletRequest
• HttpServletRequest is an interface and extends the ServletRequest
interface. By extending the ServletRequest this interface is able to allow
request information for HTTP Servlets.

• Object of the HttpServletRequest is created by the Servlet container and,


then, it is passed to the service method (doGet(), doPost(), etc.) of the
Servlet.
HttpServletRequest Methods
i. public String getAuthType()
Returns the name of the authentication scheme used to
protect the servlet.
ii. public String getContextPath ()
Returns the portion of the request URI that indicates the
context of the request.
iii. public Cookie [] getCookies ( )
Returns an array containing all of the cookie objects the
client sent with this request.
iv public long getDateHeader(String name)
Returns the value of the specified request header as a long
value that represents a date object.
v public String getHeader(String name)
Returns the value of the specified request header as a string.
HttpServletRequest Methods(cont..)
vi. public Enumeration getHeaderNames()
Returns an enumeration of all the header names this request
contains.
vii. public Enumeration getHeaders (String name)
Returns all the values of the specified request header as an
enumeration of String objects.
viii. public int getIntHeader (String name)
Returns the value of the specified request header as an int.
ix. public String getMethod()
Returns the name of the HTTP method with which this request
was made, for example, GET, POST, or PUT, same as the
value of the CGI variable REQUEST_METHOD.
x. public String getPathlnfo()
Returns any extra path information associated with the URL
the client sent when it made this request.
Life Cycle of a Servlet (Servlet Life Cycle)

• The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Life Cycle of a Servlet (Servlet Life Cycle)

1) Servlet class is loaded


• The classloader is responsible to load the servlet class. The servlet class
is loaded when the first request for the servlet is received by the web
container.
2) Servlet instance is created
• The web container creates the instance of a servlet after loading the
servlet class. The servlet instance is created only once in the servlet life
cycle.
3) init method is invoked
• The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is the
life cycle method of the javax.servlet.Servlet interface. Syntax of the init
method is given below:
• public void init(ServletConfig config) throws ServletException
Life Cycle of a Servlet (Servlet Life Cycle)
4) service method is invoked
• The web container calls the service method each time when request for
the servlet is received. If servlet is not initialized, it follows the first three
steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized
only once. The syntax of the service method of the Servlet interface is
given below:
• public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
• The service () method is called by the container and service method
invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So
you have nothing to do with service() method but you override either
doGet() or doPost() depending on what type of request you receive from
the client.
Life Cycle of a Servlet (Servlet Life Cycle)

• The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
The doGet() Method
• A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
• public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { // Servlet code }
The doPost() Method
• A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
• public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { // Servlet code }
Life Cycle of a Servlet (Servlet Life Cycle)

5) destroy method is invoked


• The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:
• public void destroy()
Steps to create a servlet example

• There are given 6 steps to create a servlet example. These steps are required for all the servers.
Create and compile servelet code
Add the mapping to web.xml file
Start Apache tomcat
Start web browser and request a server.
The servlet example can be created by three ways:
• By implementing Servlet interface,
• By inheriting GenericServlet class, (or)
• By inheriting HttpServlet class
• The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Steps to create a servlet example

• Here, we are going to use apache tomcat server in this example.

The steps are as follows:


• Create a directory structure
• Create a Servlet
• Compile the Servlet
• Create a deployment descriptor
• Start the server and deploy the project
• Access the servlet
Sample Code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
private String message;
public void init() throws ServletException
{
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}}
Cookies in Servlet
• A cookie is a small piece of information that is persisted between the
multiple client requests.
• A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version
number.

Types of Cookie
• Non-persistent cookie
• Persistent cookie
Non-persistent cookie
• It is valid for single session only. It is removed each time when user
closes the browser.
Persistent cookie
• It is valid for multiple session . It is not removed each time when
user closes the browser. It is removed only if user logout or signout.
Cookie class

• javax.servlet.http.Cookie class provides the functionality of using cookies. It


provides a lot of useful methods for cookies.
Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified


name and value.
Cookie class
Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in
seconds.

public String getName() Returns the name of the cookie. The name
cannot be changed after creation.

public String getValue() Returns the value of the cookie.


public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.

For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces:
• public void addCookie(Cookie ck):method of HttpServletResponse interface is
used to add cookie in response object.
• public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.
Simple example of Servlet Cookies
index.html

<form action="servlet1" method="post">


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response

out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
} }
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


{
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
}
}
web.xml
• <web-app> • <servlet-name>s2</servlet-name>
• <servlet> • <servlet-class>SecondServlet</servlet-
• <servlet-name>s1</servlet-name> class>
• <servlet-class>FirstServlet</servlet-class> • </servlet>
• </servlet>
• <servlet-mapping>
• <servlet-mapping> • <servlet-name>s2</servlet-name>
• <servlet-name>s1</servlet-name> • <url-pattern>/servlet2</url-pattern>
• <url-pattern>/servlet1</url-pattern> • </servlet-mapping>
• </servlet-mapping> • </web-app>
• <servlet>
Event and Listener in Servlet

• Event classes and Listener interfaces in the javax.servlet and javax.servlet.http packages

Event interfaces
Event classes The event interfaces are as follows:
The event classes are as follows: ServletRequestListener
ServletRequestEvent ServletRequestAttributeListener
ServletContextEvent ServletContextListener
ServletRequestAttributeEvent ServletContextAttributeListener
ServletContextAttributeEvent HttpSessionListener
HttpSessionEvent HttpSessionAttributeListener
HttpSessionBindingEvent HttpSessionBindingListener
HttpSessionActivationListener
Summary
. Discussed about Java Servlet.
. Discussed about Servlet Life Cycle.
. Discussed about Http request and response.

39
Home Work
Q1. Difference between Generic and http Servlet?

Q2. State the Life Cycle of Servlet?

40
References

Online Video Link


• https://nptel.ac.in/courses/106/105/106105191/
• https://www.coursera.org/courses?query=java
• https://www.coursera.org/specializations/object-oriented-programming
• https://www.youtube.com/watch?v=aqHhpahguVY

Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .

41
THANK YOU

For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)

Lecture - 29 DISCOVER . LEARN . EMPOWER


JAVA SERVER PAGES
Chapter Course Objectives

● To understand about Java Server Pages (JSP).


● To understand about JSP Architecture.
19.
● To understand about JSP Life Cycle.

Chapter Course Outcomes


After completion of this course, student will be able to
● Learn the basic JSP and its Architecture.
19.
● Learn about JSP Life Cycle.

2
JAVA SERVER PAGE (JSP)
What is JSP?
• Java Server Pages (JSP) is a technology which is used to develop web
pages by inserting Java code into the HTML pages by making special JSP
tags.
• The JSP tags which allow java code to be included into it are <% ----java
code----%>.
• It is a server side technology.
• It is used for creating web application.
• It is used to create dynamic web content.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform
independent web pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the
client’s request.
Servlet Vs JSP
Servlets – JSP –
•Servlet is a Java program which •JSP program is a HTML code which
supports HTML tags too. supports java statements too.To be
•Generally used for developing more precise, JSP embed java in html
business layer(the complex using JSP tags.
computational code) of an enterprise •Used for developing presentation
application. layer of an enterprise application
•Servlets are created and maintained •Frequently used for designing
by Java developers. websites and used by web developers.
JSP syntax
1.Declaration Tag :-It is used to declare variables.
Syntax:- <%! Dec var %>
Example:- <%! int var=10; %>

2.Java Scriplets :- It allows us to add any number of


JAVA code, variables and expressions.
Syntax:- <% java code %>
3.JSP Expression :- It evaluates and convert the expression to a string.

Syntax:- <%= expression %>


Example:- <% num1 = num1+num2 %>

4.JAVA Comments :- It contains the text that is added for information


which has to be ignored.
Syntax:- <% -- JSP Comments %>
JSP Architecture
JSP Architecture(cont..)
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
•As with a normal page, your browser sends an HTTP request to the web server.
•The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
This is done by using the URL or JSP page which ends with .jsp instead of .html.
•The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is
very simple in which all template text is converted to println( ) statements and all JSP elements are
converted to Java code. This code implements the corresponding dynamic behavior of the page.
•The JSP engine compiles the servlet into an executable class and forwards the original request to a
servlet engine.
•A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format. The output is furthur passed on to the web
server by the servlet engine inside an HTTP response.
•The web server forwards the HTTP response to your browser in terms of static HTML content.
•Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response
exactly as if it were a static page.
JSP Life Cycle
The following are the paths followed by a JSP −
• Compilation
• Initialization
• Execution
• Cleanup
JSP tag

• The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
JSP Scriplet tag
• A scriptlet tag is used to execute java source code in JSP.
Syntax is as follows:
• <% java source code %>

Example:
• <html>
• <body>
• <% out.print("welcome to jsp"); %>
• </body>
• </html>
JSP expression tag
• The code placed within JSP expression tag is written to the
output stream of the response. So you need not write
out.print() to write data. It is mainly used to print the values
of variable or method.
• Syntax of JSP expression tag
• <%= statement %>
• Example:
• <html>
• <body>
• <%= "welcome to jsp" %>
• </body>
• </html>
JSP Declaration Tag
• The JSP declaration tag is used to declare fields and methods.
• The code written inside the jsp declaration tag is placed outside
the service() method of auto generated servlet.
• So it doesn't get memory at each request.
• The syntax of the declaration tag is as follows:
• <%! field or method declaration %>
• Example:
• <html>
• <body>
• <%! int data=50; %>
• <%= "Value of the variable is:"+data %>
• </body>
• </html>
Summary
. Discussed about Java Server Pages (JSP).
. Discussed about JSP Architecture.
. Discussed about JSP Life Cycle.

15
Home Work
Q1. What are the life-cycle methods for a JSP?

Q2. List out some advantages of using JSP.

16
References

Online Video Link


• https://nptel.ac.in/courses/106/105/106105191/
• https://www.coursera.org/courses?query=java
• https://www.coursera.org/specializations/object-oriented-programming
• https://www.youtube.com/watch?v=aqHhpahguVY

Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .

17
THANK YOU

For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)

Lecture -30 &31 DISCOVER . LEARN . EMPOWER


DATABASE Connectivity in JAVA
Chapter Course Objectives

● To understand about Database.


20. ● To understand about Database connectivity with java.

Chapter Course Outcomes


After completion of this course, student will be able to
● Learn about the database.
20.
● Learn about Database connectivity with java.

2
Data Base Connectivity in JAVA
Java JDBC
• JDBC stands for Java Database Connectivity.
• JDBC is a Java API to connect and execute the query with the database.
• It is a part of JavaSE (Java Standard Edition).
• JDBC API uses JDBC drivers to connect with the database.

There are four types of JDBC drivers:


• JDBC-ODBC Bridge Driver(Type1)
• Native Driver(Type2)
• Network Protocol Driver(Type3)
• Thin Driver(Type4)
Java JDBC
• The java.sql package contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
JDBC Driver

• JDBC Driver is a software component that enables java application to interact with the
database.

There are 4 types of JDBC drivers:


• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to
the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now
discouraged because of thin driver.
2) Native-API driver
• The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
3) Network Protocol driver
• The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.
4) Thin driver
• The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Java Database Connectivity with 5 Steps

• There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
1) Register the driver class
• The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.

Syntax of forName() method:


• public static void forName(String className)throws ClassNotFoundException

Ex:
• Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object

• The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
• 1) public static Connection getConnection(String url)throws SQLException
• 2) public static Connection getConnection(String url,String name,String password) throws SQLException

Ex:
• Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object

• The createStatement() method of Connection interface is used to create statement.


• The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method


• public Statement createStatement()throws SQLException

Ex:
• Statement stmt=con.createStatement();
4) Execute the query
• The executeQuery() method of Statement interface is used to execute queries to
the database.
• This method returns the object of ResultSet that can be used to get all the records
of a table.
Syntax of executeQuery() method:
• public ResultSet executeQuery(String sql)throws SQLException
Ex:
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next())
• {
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }
5) Close the connection object

• By closing connection object statement and ResultSet will be closed automatically.


• The close() method of Connection interface is used to close the connection.
Syntax of close() method
• public void close()throws SQLException
Ex:
• con.close();
Java Database Connectivity with Oracle

Create a Table
• Before establishing connection, let's first create a table in oracle database.
• Following is the SQL query to create a table.
• create table emp(id number(10),name varchar2(40),age number(3))
;
Ex:Database Connectivity
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}


} }
Statement interface
• The Statement interface provides methods to execute queries with the database.

The important methods of Statement interface are as follows:


1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It
returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may
be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a row of a table.
• Initially, cursor points to before the first row.
1) public boolean next(): is used to move the cursor to the one row next from the current position.

2) public boolean previous(): is used to move the cursor to the one row previous from the current position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object.

6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or
negative.

7) public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int.

8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int.

9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.

10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.
Ex:ResultSet
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracl
e");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_U
PDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}
PreparedStatement interface
• The PreparedStatement interface is a subinterface of Statement.
• It is used to execute parameterized query.
Example of parameterized query:
• String sql="insert into emp values(?,?,?)";

Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.

public void setString(int paramIndex, String value) sets the String value to the given parameter index.

public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.
Ex:PreparedStatement
First of all create table as given below:
create table emp(id number(10),name varchar2(50));

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);} } }
Java ResultSetMetaData Interface
• The metadata means data about data i.e. we can get further information from the data.
• If you have to get metadata of a table like total number of column, column name, column type etc.
, ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified column
SQLException index.

public String getColumnTypeName(int index)throws it returns the column type name for the specified
SQLException index.

public String getTableName(int index)throws it returns the table name for the specified column
SQLException index.
Ex:ResultSetMetaData
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
store image in Oracle database
• You can store images in the database in java by the help of PreparedStatement interface.
• The setBinaryStream() method of Prepared Statement is used to set Binary information into the
parameter Index.

Methods:
1) public void setBinaryStream(int paramIndex,InputStream stream) throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream, long length) throws SQLException
Ex: Image Store
• For storing image into the database, BLOB (Binary Large Object) data type is used in the table.
For example:
• CREATE TABLE "IMGTABLE" ( "NAME" VARCHAR2(4000), "PHOTO" BLOB )
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle")
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1,“Dog");
FileInputStream fin=new FileInputStream("d:\\g.jpg");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();} } }
CallableStatement Interface
• CallableStatement interface is used to call the stored procedures and functions.

Syntax:
• public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

Ex:
• CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
Ex:
To call the stored procedure, you need to create it in the database. Here, we are assuming that
stored procedure looks like this.
create or replace procedure "INSERTR"
(id IN NUMBER,name IN VARCHAR2)
is begin
insert into user values(id,name);
end;

The table structure is given below:


create table user420(id number(10), name varchar2(200));
Ex:(cont..)
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");

CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");


stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

System.out.println("success");
}
}
Singleton Class
Singleton design pattern in Java

• Singleton Pattern says that just"define a class that has only one instance and
provides a global point of access to it".
• In other words, a class must ensure that only single instance should be created
and single object can be used by all other classes.

There are two forms of singleton design pattern:


• Early Instantiation: creation of instance at load time.
• Lazy Instantiation: creation of instance when required.
Singleton design pattern in Java
Advantage of Singleton design pattern
• Saves memory because object is not created at each request.
• Only single instance is reused again and again.

Usage of Singleton design pattern


• Singleton pattern is mostly used in multi-threaded and database applications.
• It is used in logging, caching, thread pools, configuration settings etc.
How to create Singleton design pattern?

• To create the singleton class, we need to have static member of class, private constructor and
static factory method.
• Static member: It gets memory only once because of static, it
contains the instance of the Singleton class.
• Private constructor: It will prevent to instantiate the Singleton class
from outside the class.
• Static factory method: This provides the global point of access to
the Singleton object and returns the instance to the caller.
Ex:1
• class A{
• private static A obj=new A();//Early, instance will be created at load time
• private A(){}

• public static A getA(){
• return obj;
• }

}
Ex:2
• class A{
• private static A obj;
• private A(){}
• public static A getA(){
• if (obj == null){
• synchronized(Singleton.class){
• if (obj == null){
• obj = new Singleton();//instance will be created at request time
• }
• }
• return obj;
•}
Summary
. Discussed about Database.
. Discussed different types database connectivity with java.

37
Home Work
Q1. What is JDBC Driver?

Q2. What are the steps to connect to the database in java?

38
References

Online Video Link


• https://nptel.ac.in/courses/106/105/106105191/
• https://www.coursera.org/courses?query=java
• https://www.coursera.org/specializations/object-oriented-programming
• https://www.youtube.com/watch?v=aqHhpahguVY

Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .

39
THANK YOU

For queries
Email: kushagra.e13465@cumail.in

You might also like