0% found this document useful (0 votes)
83 views

Web Tech Notes (Unit-3 & 4)

Uploaded by

hrithik7001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Web Tech Notes (Unit-3 & 4)

Uploaded by

hrithik7001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT -3

Scripting
1. JavaScript is a scripting language which enables web authors to design
Inter active sites.
2. JavaScript can interact with HTML source code, enabling web authors
to build their sites with dynamic content.
3. JavaScript is an open source language that anyone can use without
purchasing a license.

Working of Java Script:

1. When the browser loads a web page, the HTML parser creates the DOM.
2. Whenever parser encounters JavaScript directive, it is handed over the
JavaScript engine and loads the external and inline code.
3. After HTML and CSS parsing is completed, JavaScript is executed in
order they were found in web page and DOM is updated and rendered
by the browser.

JavaScript has several features :

1. Programming tool : JavaScript is a scripting language with very simple


syntax.
2. Can produce dynamic text into an HTML page : For instance, the
JavaScript statement - document.write (“<h1>”+name+ “</h1>”); results
into the HTML output <h1> Atul </h1>, if the variable name contains
the text Atul.
3. Reaching to events : JavaScript code executes when something
happens such as when page has finished loading, when a user clicks on
an HTML element.
4. Reading and writing HTML elements : JavaScript can read and
change the content of an HTML element.
5. Validate data : JavaScript can be used to validate form data before it is
submitted to a server, and thus saves the server from extra processing.
Que 3.2. Difference between Java and Java Script -

S. No. Java JavaScript


1. Java is an object-oriented JavaScript is an object based
programming language. scripting language.
2. Java is strongly typed language JavaScript is very flexible in
and type checking. data type.
3. Objects in Java are static. Objects in JavaScript are
dynamic.
4. It can be used to create It cannot be used to create
standalone application. standalone application.
5. Variables in Java are declared Variables in JavaScript are
as : int num. declared as : var myname.

Strengths/Advantages of JavaScript :
1. An interpreted language : JavaScript is an interpreted language,
which requires no compilation steps.
2. Quick development : JavaScript does not require time consuming
compilations, scripts can be developed in a short period of time.
3. Performance :
a. JavaScript can be written such that the HTML files are fairly compact
and quite small.
b. It minimizes storage requirements on the web server and download
time for the client.
4. Easy debugging and testing : Being an interpreted language, scripts
in JavaScript are tested line by line and the errors are also listed as they
are encountered.
Weakness/Disadvantages of JavaScript :
1. There are issues of incompatibility of several scripting that result in
website overloading.
2. Different layout engines may render JavaScript differently resulting in
inconsistency in terms of functionality and interface.
3. JavaScript is also a common tool for the web hackers; they use scripts
injection to hack a site.
4. JavaScript is light, somehow too much of JavaScript can slow down the
page loading of a website.
Java Script DOM -

1. A document object represents the HTML document that is displayed


in the window.
2. DOM is an object oriented representation of an HTML document and
acts as an interface between JavaScript and the document itself and
allows the creation of dynamic web pages.
3. The hierarchical structure of object is applied for the organization of
objects in a web document which include following object :
a. Window object: It is the top most element of the object hierarchy.
b. Document object: Each HTML document that gets loaded into a
window becomes a document object which contains the contents of
the page.
c. Form object: Everything enclosed in the <form>...</form> tags
sets the form object. The form object contains all the elements
defined for that object such as text fields, buttons, radio buttons,
and checkboxes.
4. When a web page is loaded, the browser creates a Document Object
Model of the page.
5. DOM supports navigation in any direction (i.e., parent and previous
sibling) and allows for arbitrary modifications.

Steps used to perform client-side validation using Java-

Script :
1. First the user will enter the value in the form field.
2. Then, browser will ensure that the value provided by user is correct and
is valid so that successful validation can be done.
3. JavaScript used in the web page uniquely defines all the special
functionalities in the client browser.
4. By default, if there is a validation error then an error or pop-up message
is shown by the browser.
5. If there is no error then the validation on client-side will be successfully
performed.
For example :
If a form field (fname) is empty, validateform function alerts a message,
and returns false, to prevent the form from being submitted:
function validateForm() {
var x = document.forms[“myForm”][“fname”].value;
if (x == “ ”) {
alert(“Name must be filled out”);
return false;
}
}
The JavaScript function is called when the form is submitted :
<form name=“myForm” action=“/action_page.php” onsubmit=“return
validateForm()” method=“post”>
Name: <input type=“text” name=“fname”>
<input type=“submit” value=“Submit”>
</form>

Scripting language :
1. A scripting language is a programming language designed for integrating
and communicating with other programming languages.
2. Some of the most widely used scripting languages are JavaScript,
VBScript, PHP, Perl, Python, Ruby, ASP.
JavaScript is used because :
a. It is executed on client side.
b. It saves bandwidth on web server.
c. It is written into an HTML page.

JavaScript function for validating form data :


<script type=“text/javascript”>
function validateform()
{
var name = document.myform.name.value;
var password = document.myform.password.value;
var confirmpassword = document.myform.password2.value
var email = document.myform.email.value;# Username validation
if (name == null || name == “”){
alert(“Name can’t be blank”);
return false;
}else if(password.length<6){
alert(“Password must be at least 6 characters long.”);
return false;
}
}
# Retype password validation
if (password == confirmpassword){
return true;
}
else{
alert(“password must be same!”);
return false;
}
}
# Email validation
var emailErr = True;
if(email == “”) {
printError(“emailErr”, “Please enter your email address”);
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError(“emailErr”, “Please enter a valid email address”);
} else{
printError(“emailErr”, “”);
emailErr = false;
}
}
</script>
<body>
<form name=“myform” method=“post” onsubmit=“return validateform()”>
Username: <input type=“text” name=“name”><br/>
Password : <input type=“password” name=“password” /><br/>
Re-enter Password: <input type=“password” name=“password2”/><br/>
Email : <input type=“text” name=“email”>
<div class=“error” id=“emailErr”></div>
<input type=“submit” value=“Register”>
</form>
</body>
</html>

Program to sort value using JavaScript :


<!DOCTYPE html>
<html><body>
<h2>JavaScript Array Sort</h2>
<p>The sort() method sorts an array alphabetically.</p>
<button onclick=“myFunction()”>Try it</button>
<p id=“demo”></p>
<script>
var fruits = [“Banana“, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById(“demo”).innerHTML = fruits;
}
</script>
</body>
</html>

Role of Java Script :


1. It makes our website dynamic.
2. It makes our webpage interactive which means that it can respond to
mouse clicks, double clicks, hover and many other actions (called events).
3. It can also be used for modifying our html, content and styles, form
validation.
4. JavaScript can interact with the website server to send and receive
information to update UI in real-time.
JavaScript function to check whether a textbox is either empty or
not :
<html>
<script>
function required(inputtx)
{
if (inputtext1.value.length == 0)
{
alert(“Textbox is empty”);
return false;
}
return true;
}
</script>
<body>
<form>
<input type = “text” name=“text1”>
</form>
</body></html>

Conditional Statement In Java Script :


1. If statement : If statement is used if we want to execute some code
only if a specified condition is true.

Syntax :
if (condition)
{
code to be executed if condition is true
}
For example :
<script type = “text/javascript”>
var d = new Date();
var time = d.getHours();
if (time<10)
{
document.write (“<b>Good morning to all</b>”);
}
</script>
2. If...else statement : If...else statement is used when we do not confirm
about the condition that is true or not.
Syntax :
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
For example :
<script type = “text/javascript”>
//If the time is less than 10, print “Good Day” Otherwise “Good Night”
var d = new Date ();
var time = d.getHours ();
if (time < 10)
{
document.write (“Good Day”);
}
else
{
document.write (“Good Night”);
}
</script>
3. If...else if...else statement : We can use the if...else if...else statement
if we want to select one from many sets of lines with different condition.
Syntax :
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}
For example :
<script type = “text/javascript”>
var d = new Date();
var time = d.getHours();
if (time<10)
{
document.write(“<b>Good morning</b>”);
}
else if (time>10 && time<16)
{
document.write(“<b>Good afternoon</b>”);
}
else
{
document.write (“<b>Good night</b>”);
}
</script

4-Switch statement : If we want to select one of many blocks of code then


we use switch statement.
Syntax :
switch(n)
{
case 1 :
execute code block 1
break ;
case 2 :
execute code block 2
break ;
default ;
code to be executed if n is different from case 1 and 2
}
For example :
<script type = “text/javascript”>
var d=new Date();
theDay=d.getDay();
switch(theDay)
{
case 1 :
document.write(“Finally Monday”);
break ;
case 2 :
document.write(“Super Tuesday”);
break ;
case 0 :
document.write(“Sleepy Sunday”);
break ;
default :
document.write(“I’m looking forward to this weekend!”);
}
</script>

Function in Java Script :


1. Functions can be defined both in the <head> and in the <body> section
of a document.
2. However, to assure that the function is read/loaded by the browser
before it is called, it is needed to be defined in the <head> section.
3. Syntax :
function function_name (var1, var2, . . . , varX)
{
some code
}
var1, var2, etc., are variables or values passed into the function.
4. A function with no parameters must include the parentheses () after
the function name.

Object in JavaScript :
1. Built-in objects : These objects are used quite extensively for data
processing in JavaScript. Following are some built-in object :
a. String object :
i. The string object enables programs to work with and manipulate
string.
ii. It provide methods such as : big(), blink(), bold(), italics(),
charAt(), touppercase(), tolowercase() and substring().
b. Math object :
i. The math object provides some commonly used methods such
as : sqrt(num), abs(num), sin(num), cos(num), tan(num),
exp(num), min(a, b), max(a, b), log(num), pow(a, b), floor(num),
ceil(num) etc.
c. Date object :
i. The date object enables JavaScript programmers to create an
object that contains information about a particular date and
provides a set of methods to work with that information.
ii. Syntax :
var mydate = new Date(<parameters>);
iii. If the parameter left empty, it indicates current date and time.
iv. The date object provides some methods which are : getDate(),
setDate(), getHours(), setHours(), getTime(), setTime(),
getDay(), setDay(), getMinutes(), setMinutes(), getSecond(),
setSecond().
d. Array object :
i. The array object stores multiple values in a single variable.
ii. Syntax :
var fruits = new Array( “apple”, “orange”, “mango” );
2. User-defined objects :
a. A user-defined object is also associated with properties and
methods, which belong to it.
b. The user-defined object would also require methods that will
allow
the storage of name, age and salary of the employee object.
function Employee(name, age, salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}
Introduction of AJAX –

1. AJAX (Asynchronous JavaScript and XML) is a set of web development


techniques for creating better, faster and more interactive web
applications with the help of XML, HTML, CSS and JavaScript.
2. Traditional web applications tend to follow the pattern .
3. First a page is loaded. Next, the user performs some action such as
filling out a form or clicking a link.
4. The user activity is then submitted to a server-side program for processing
while the user waits until final result is sent which reloads the entire
page.
Advantages of AJAX :
1. Reduces the server traffic and increases the speed.
2. Ajax is responsive and time for data transfer is also less.
3. Form validation
4. Bandwidth usage can be reduced.
Asynchronous calls can be made which reduces the time for
data arrival.

Working of AJAX : XML Http Request object plays an important role as


AJAX communicates with the server using XML Http Request object.
1. User sends a request from the UI and a JavaScript call goes to
XML Http Request object.
2. HTTP request is sent to the server by XML Http Request object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net
etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XML Http Request
callback function.
6. HTML and CSS data is displayed on the browser.

Browser Web server

2 HTTP request
XMLHttp Request Business logic
implementation

callback() (PHP, servlet, etc.)


5 XML Data
1
JavaScript 6
call data
HTML & 4
3 exchange
CSS data

Presentation Data Store


Applications of AJAX are :-
1. AJAX is used to change the text without reloading the web page.
2. AJAX is a technique used for creating fast and dynamic web pages.
3. AJAX contains div section which is used to display information returned
from a server.
4. Major application of AJAX is in login forms where user can enter their
login details directly on the original page.

IP Addressing-
1. The IP address is a network layer address that uniquely identifies each
computer on network.
2. Each TCP/IP host is identified by a logical IP address.
3. The IP address identifies a system’s location on the network. An IP
address must be globally unique and have a uniform format.
4. Each IP address includes a network ID and a host ID.
i. The network ID (also known as a network address) identifies the
systems that are located on the same physical network ID. The
network ID must be unique to the internetwork.
ii. The host ID (also known as a host address) identifies a workstation,
server, router, or other TCP/IP host within a network. The address
for each host must be unique to the network ID.
5. The use of the term network ID refers to any IP network ID, whether
it is class-based, a subnet, or a super net.
An internet address is made of four
bytes (32 bits) that define a host's
connection to a network.

Class
type Netid Hostid

6. An IP address is 32 bits long. It is a common practice to segment the 32


bits of the IP address into four 8-bit fields called octets.
7. Each octet is converted to a decimal number (the base 10 numbering
system) in the range 0-255 and separated by a period (a dot). This
formal is called dotted decimal notation.

IP Address-
IP address is classified as:
1. Class A :
i. Class A addresses are assigned to networks with a very large
number of hosts.
ii. The high-order bit in a class A address is always set to zero.
iii. The next seven bits (completing the first octet) complete network
ID. The remaining 24 bits (the last three octets) represent the
host ID.
iv. This allows for 126 networks and 16,777,214 i.e., 2 24 hosts per
network.
2. Class B :
i. Class B addresses are assigned to medium-sized to large-sized
networks.
ii. The two high-order bit in a class B address are always set to binary
10.
iii. The next 14 bits (completing the first two octets) complete the
network ID. The remaining 16 bits (last two octets) represent the
host ID.
iv. This allows for 16,384 networks and 65,534 hosts per network.
byte 1 byte 2 byte 3 byte 4

Class A 0 Netid Hostid


Class B 10 Netid Hostid

Class C 110 Netid Hostid

Class D 1110 Multicast address

Class E 1111 Reserved for future use

3. Class C :
i. Class C addresses are used for small networks.
ii. The three high-order bits in a class C address are always set to
binary 110.
iii. The next 21 bits (completing the first three octets) complete the
network ID. The remaining 8 bits (last octet) represent the host
ID.
iv. This allows for 2,097, 152 networks and 254 hosts per network.
From To
Class A 0.0.0.0 127 . 255 . 255 . 255
Netid Hostid Netid Hostid
Class B 128 . 0 . 0 . 0 191 . 255 . 255 . 255
Netid Hostid Netid Hostid
Class C 192 . 0 . 0 . 0 223 . 255 . 255 . 255
Netid Hostid Netid Hostid
Class D 224 . 0 . 0 . 0 239 . 255 . 255 . 255
Group address Netid Hostid
Class E 240 . 0 . 0 . 0 255 . 255 . 255 . 255
Undefined Undefined

Figure

4. Class D :
i. Class D addresses are reserved for IP multicast addresses.
ii. The four high-order bits in a class D address are always set to
binary 1110.
iii. The remaining bits are for the address that interested hosts will
recognize.
iv. Microsoft supports class D addresses for applications to multicast
data to multicast-capable hosts on an internetwork.
5. Class E : Class E addresses are experimental addresses reserved for
future use. The high-order bits in a class E address are set to 1111
Inet Address class
1. The InetAddress class is used to encapsulate both the numerical IP
address and the domain name for that address.
2. The InetAddress class hides the number inside.
3. InetAddress can handle both IPv4 and IPv6 addresses.
4. The InetAddress class has no visible constructors.
Factory Methods-
1. Factory methods are used to create an InetAddress object.
2. Factory method is a static method in a class and return an instance of
that class.
3. Three commonly used InetAddress factory methods are as follows :
a. The getLocalHost() : This method simply returns the InetAddress
object that represents the local host.
b. The getByName() : This method returns an InetAddress for a
host name passed to it. If this method is unable to resolve the
host name then, they throw an UnknownHostException.
c. The getAllByName() : This method returns an array of
InetAddresses that represent all of the addresses that a particular
name resolves to. It will also throw an UnknownHostException
if it cannot resolve the name to at least one address.

Instance Method-
1. Instance method is a method defined in a class and only accessible
through the object of the class.
2. The InetAddress class has several instance methods, which can be
used on the objects.
3. Following are the object returned by the methods which are as follows :
a. Boolean equals(Object other) : It returns true if this object
has the same Internet address as other. Otherwise, it returns
false.
b. Byte[ ] getAddress() : It returns a byte array that represents
the object’s Internet address in network byte order.
c. String getHostAddress() : It returns a string that represents
the host address associated with the Inet Address object.
d. String getHostName() : It returns a string that represents the
host name associated with the InetAddress object.
e. String toString() : It returns a string that lists the host name
and the IP address.
TCP/IP Client Sockets
1. TCP/IP client sockets are used to implement bi-directional, point-to-
point, stream-based connections between hosts on the Internet.
2. A socket can be used to connect Java I/O system to other programs
that may reside either on the local machine or on any other machine
on the Internet.
3. The creation of a Socket object implicitly establishes a connection
between the client and server.
4. Following are the two constructors used to create client socket :
a. Socket(String hostName, int port) : Creates a socket connecting
the local host to the named host, port and can throw an Unknown
HostException or an IOException.
b. Socket(InetAddress ipAddress, int port) : Creates a socket
using a pre-existing InetAddress object, a port and can throw an
IOException.
5. Following methods are used by TCP/IP client socket :
a. InetAddress getInetAddress() : Returns the InetAddress
associated with the Socket object.
b. Int getPort() : Returns the remote port to which the Socket
object is connected.
c. Int getLocalPort() : Returns the local port to which the Socket
object is connected.
URL
1. URL is an acronym for Uniform Resource Locator.
2. It points to a resource on the World Wide Web (WWW).
3. A URL contains many information like protocol name, server name,
port number and file name.
4. The URL is represented by an URL class.
5. Consider the following URL :
http://www.quantumpage.com/aktu-paper.html
a. Protocol : In this case, http is the protocol.
b. Server name or IP address : In this case, www.quantumpage.com
is the server name.
c. Port number : It is an optional attribute. If we write http//
www.quantumpage.com:80/aktu-papers.html/, 80 is the port
number. If port number is not mentioned in the URL, it returns
– 1.
d. File name or directory name : In this case, aktu-papers.html
is the file name.
Following are the method provided by java.net.URL class :
S. No. Method Description

1. public String getProtocol() It returns the protocol of the URL.


2. public String getHost() It returns the host name of the URL.
3. public String getPort() It returns the Port Number of the
URL.
4. public String getFile() It returns the file name of the URL.
5. public URLConnect ion It returns the instance of
openConnection() URLConnection i.e., associated with
this URL.

URL Connection class


1. The Java URLConnection class represents a communication link between
the URL and the application.
2. This class can be used to read and write data to the specified resource
referred by the URL.
3. The openConnection() method of URL class returns the object of
URLConnection class.
4. Syntax to get the object of URLConnection :
public URLConnection openConnection()throws IOException{}
5. The URLConnection class use getInputStream() method to display all
the data of a web page.
6. The getInputStream() method returns all the data of the specified
URL in the stream that can be read and displayed.

TCP/IP server socket.


1. The TCP/IP Server Socket is used to create servers that listen for
either local or remote client programs to connect them on published
ports.
2. TCP/IP Server Sockets are quite different from normal sockets.
3. When we create a TCP/IP Server Socket, it will register itself with the
systems that have client connections.
4. The constructors for TCP/IP Server Socket reflect the port number
that we wish to accept connections on and, how long we want the port
to be in the queue.
5. The queue length tells the system how many client connections it can
leave pending before it should simply refuse connections.
6. It has constructors that create new TCP/IP Server Socket objects,
methods that listen for connections on a specified port, methods that
configure the various TCP/IP server socket options, and the usual
miscellaneous methods such as to String().

Socket Programming
1. Java socket programming is used for communication between the
applications running on different JRE.
2. Java socket programming can be connection-oriented or connection-
less.
3. Socket and Server Socket classes are used for connection-oriented socket
programming and Datagram Socket and Datagram Packet classes are
used for connection-less socket programming.
4. Sockets provide the communication mechanism between two computers
using TCP.
5. A client program creates a socket on its end of the communication and
attempts to connect that socket to a server.
6. The client in socket programming must know :
a. IP address of server.
b. Port number.
Datagram Sockets

1. Datagram is a unit of transfer associated with networking.


2. Datagram is typically structured in header and payload section.
3. It provides a connectionless communication service across a
packet-switched network.
Characteristics of Datagram:
1. It is transmitted from source to destination without guarantee of delivery.
2. It provides a connectionless communication service.

Advantage Datagram Socket-


1. It is a communication link used to send datagram between applications.
2. Datagram socket is a type of network socket which provide
connectionless point for sending and receiving packets.
3. Every packet sent from a datagram socket is individually routed and
delivered.
4. Java Datagram Socket and Datagram Packet classes are used for
connectionless socket programming.
5. A Datagram Packet is a message that can be sent or received through
Datagram Socket.
6. Commonly used constructors of Datagram Socket class are as follows :
a. Datagram Socket() throws Socket Exception : It creates a
datagram socket and binds it with the available port number on
the local host machine.
b. Datagram Socket(int port) throws Socket Exception : It
creates a datagram socket and binds it with the port number.
c. Datagram Socket(int port, int Address address) throws
Socket Exception : It creates a datagram socket and binds it
with the specified port number and host address.
UNIT- 4

Enterprise Java Bean(EJB)


1. An Enterprise Java Bean is a server-side component which encapsulates
business logic.
2. EJB (Enterprise Java Bean) is used to develop scalable, robust and
secured enterprise applications in Java.
3. Middleware services such as security, transaction management etc. are
provided by EJB container to all EJB applications.
4. To run EJB application, we need an application server (EJB Container)
such as Jboss, Glassfish, Weblogic, Websphere etc.
5. EJB application is deployed on the server, so it is also called server-side
component.

Advantages of EJB :
1. It can run in multithreaded environment.
2. It contains only business logic.
3. EJB provides distributed transaction support.
4. It provides portable and scalable solutions of the problem.
5. It provides a mechanism to store and retrieve data in a persistent way.

Disadvantages of EJB :
1. It requires application server.
2. It requires only Java client. For other language client, we need to go for
web service.
3. It is complex to understand and develop EJB applications.
EJB Architecture

The EJB architecture is an extension of web architecture.

Working of EJB Architecture –

1. The client is working on a web browser.


2. There is a database server that hosts a database, like MySQL / Oracle.
3. The J2EE server machine is running on an application server.
4. The client interface is provided with JSP / Servlet.
5. The application server manages the relationships between the client and
database.

Types of EJB -
1. Entity bean : Entity beans represent persistent data storage. Entity
beans are used for modeling the business concept.

2. Session bean : Session beans are used for managing processes or


tasks. Hence, session beans are used for managing activities.

3. Message driven bean : Message driven bean is similar to the session


bean but it gets activated only when asynchronous message arrives.
When a message arrives then the EJB container calls the message
driven bean on message method to process the message.
Java Beans-
1. Java Beans are classes which encapsulate several objects into a single
object.
2. It helps in accessing the objects from multiple places.
3. It is a portable, platform independent model written in Java.

Steps used to create Java Bean-

Step 1 : Put source code into a file named “SimpleBean.java” :


import java.awt. * ;
import java.io.Serializable;
public class SimpleBean extends Canvas
implements Serializable {
// Constructor sets inherited properties
public SimpleBean ( ) {
setSize (60, 40);
setBackground (Color.red);
}
}

Step 2 : Compile the file :


javac SimpleBean.java

Step 3 : Create a manifest file, named “manifest.tmp” :


Name : SimpleBean.class
Java-Bean : True
Step 4 : Create the JAR file, named “SimpleBean.jar” :
jar cfm SimpleBean.jar manifest.tmp SimpleBean.class
Then, verify that the content is correct by the command “jar tf
SimpleBean.jar”.

Step 5 :
1. Start and run the Bean Box.
2. Load JAR file into Bean Box by selecting “Loadjar...” under the File
menu.
Step 6 :
1. After the file selection dialog box is closed. Then “SimpleBean” appear
at the bottom of the toolbox window.
2. Select SimpleBean.jar.
3. Cursor will change to a plus. In the middle BeanBox window, we can
now click to drop in what will appear to be a coloured rectangle.

Step 7 : Try changing the red box colour with the Properties windows.

Step 8 : Choose “Events” under the “Edit” menu in the middle window to see
what events SimpleBean can send. These events are inherited from
java.awt.Canvas.

Role of introspection in Java Bean :


1. Introspection in Java is used in the context of Java Beans which defines
the component model of Java.
2. Introspection feature enables a Java Bean to get the properties,
methods and events of other beans at runtime.
3. This helps the developers to design and develop their beans without
knowing the details of other beans.

Use of Java Beans –

1. It encapsulates many objects into a single object.


2. It allows us to use properties of getter and setter methods.
3. It has Java object which has constructor with no argument.
4. It can be manipulated visually in a builder tools.
Session Bean
1. Session bean encapsulates business logic only, it can be invoked by local,
remote and web service client.
2. It can be used for managing activities like database access, calculation
etc.
3. The life cycle of session bean is maintained by the application server
(EJB container).
4. Session bean is created by a customer and its duration is only for the
signal client server session.

Types of Session Bean-


1. Stateless session bean :
a. Stateless session bean is a business object that represents business
logic only. It does not have state (data).
b. The stateless bean objects are pooled by the EJB container to service
the request on demand.
c. It can be accessed by one client at a time.
d. The stateless session bean is distributed object which has no
connection with informal state; only allow parallel access to beans.
e. Annotations used in stateless session bean are :
i. @Stateless
ii. @PostConstruct
iii. @PreDestroy

2. Stateful session bean :


a. Stateful session bean is a business object that represents business
logic like stateless session bean. But, it maintains state (data).
b. Conversational state between multiple method calls is maintained
by the container in stateful session bean.
c. There are five important annotations used in stateful session bean :
i. @Stateful
ii. @PostConstruct
iii. @PreDestroy
iv. @PrePassivate
v. @PostActivate
3. Singleton session beans :
a. A singleton session bean is instantiated once per application and
exists for the lifecycle of the application.
b. Singleton session beans are designed for circumstances in which a
single enterprise bean instance is shared across and concurrently
accessed by clients.
c. It has only one singleton session bean per application.
d. It can implement web service endpoints.
e. Singleton session beans maintain their state between client
invocations but are not required to maintain their state across
server crashes or shutdowns.

Entity Beans-
1. Entity beans are objects that represent a persistence storage
mechanism.
2. Each entity beans has underlying table in a relational database and each
row in the table represents the instance of the bean.

Types of Entity Beans-

1. Container Managed Persistence (CMP) :


a. The term Container Managed Persistence means that the EJB container
handles all database access required by the entity bean.
b. The bean code contains no database access calls. As a result, the bean
code is not tied to a specific persistent storage mechanism (database).
c. If the same entity beans are implemented on different J2EE servers
that use different databases, we do not need to modify or recompile the
bean code.

2. Bean Managed Persistence (BMP) :


a. In this method, the entity bean provides an object view of the data.
b. A Bean Managed Persistence mechanism transforms the physical data
structure to a Java object.
c. The entity bean has code that accesses the persistence environment
directly.
d. BMP can be used to reduce the overhead of CMP.
JAVA DATABASE CONNETIVITY(JDBC)

1. JDBC (Java Database Connectivity) is a Java API that manages


connection to database, issuing queries and commands and handling
result sets obtained from the database.
2. JDBC is useful for both application developers and JDBC driver vendors.
3. JDBC is specially used for having connectivity with the RDBMS packages
using corresponding JDBC driver.

Working of JDBC :
1. All Java application establishes connection with the data source and
invokes classes and interfaces from JDBC driver for sending queries to
the data source.
2. The JDBC driver connects to corresponding database and retrieves the
result.
3. These results are based on SQL statements, which are then returned to
Java applications.
4. Java application then uses the retrieved information for further
processing.
Components of JDBC –

1.Driver manager :
a.When Java applications need connection to the database it invokes
the Driver Manager class.
b. This class then loads JDBC drivers in the memory. The driver
manager also attempts to open a connection with the desired database.
2. Connection :
a. This is an interface which represents connectivity with the datasource.
b. The connection is used for creating the statement instance.
3. Statement :
a. This interface is used for representing the SQL statements.
b. Some SQL statements are :
SELECT *FROM students _ table;
UPDATE students _table set name = ‘Nitin’ WHERE roll _ no = ‘1’;
c. There are two specialized statement types : Prepared Statement
and callable Statement.
4. Result Set :
a. This interface is used to represent the database resultSet.
b. After using SELECT SQL statement, the information obtained from
the database can be displayed using Result Set.
5. SQL exception : For handling SQL exceptions, this interface is used.
JDBC Architecture-

[1] Java application : It is a standalone Java program which


uses the JDBC API to get connected and perform operations
on the database data.

[2] JDBC API : It is a set of classes and interfaces used in a Java


program for database operations. Java.sql and Javax.sql
packages provide the necessary library support.

[3] Driver Manager : Java program uses Driver Manager class


to get theconnection with the database.

[4] Driver : It is the software that establishes connection with the


database. It is the translation software that translates the
JDBC method calls. This software enables the communication
between Java program and the database.

[5] Database : It is a collection of all enterprise data.


Types of JDBC drivers –

1. JDBC-ODBC bridge driver (Type 1 driver) :


a. These drivers are the bridge drivers such as JDBC-ODBC bridge.
b. These drivers rely on an intermediary such as ODBC to transfer
the SQL calls to the database.
c. Bridge drivers often rely on native code, although the JDBC-ODBC
library native code is part of the Java-2 virtual machine.

Application

JDBC-Driver Manager

ODBC-Driver Manager

ODBC libraries ODBC database

Fig. - JDBC-ODBC bridge driver.

2. Native API partly Java driver (Type 2 driver) :


a. A native API is partly a Java driver. It uses native C language
library calls to translate JDBC to native client library.
b. These drivers are available for Oracle, Sybase, DB2 and other client
library based RDBMS.
c. Type 2 drivers use native code and require additional permission to
work in an Applet. A Type 2 driver might need client-side
database code to connectover the network.
3. JDBC net pure Java driver (Type 3 driver) :
a. JDBC net pure Java driver consists of JDBC and DBMS independent
protocol driver.
b. Here the calls are translated and sent to middle tier server through
the socket.
c. The middle tier contacts the database.
d. Type 3 drivers call the database API on the server.

4. Native protocol pure Java driver (Type 4 driver) :


a. A native protocol Java driver contains JDBC calls that are converted
directly to the network protocol used by the DBMS server.
b. This driver interacts directly with database.

Application

JDBC

Socket connection
JAVA based (DBMS specific
DBMS
socket driver protocol)
Server

Fig. -Native protocol pure Java driver.


c. It does not require any native database library. So, it is also called
thin driver.

Steps to connect database with web application using JDBC –

Step 1 : Create a database using some suitable database management package.


Step 2 : Initiate object for JDBC driver using following statement :
Class.forName (“com.mysql.jdbc.Driver”). newInstance ( );
Step 3 : Using DriverManager class and getConnection method we get
connected to the database.
To get connected with MySQL database we use following statement :
DriverManager.getConnection (“jdbc:mysql://localhost; 3306/students”, “root”,
“system”);
Explain Prepared Statement interface in JDBC

1. Prepared statement interface is a sub interface of statement.


2. It is used to execute parameterized query.
3. The Prepared Statement interfaces define the methods and properties
that enable us to send SQL or PL/SQL commands and receive data from
our database.
4. This statement gives us the flexibility for supplying arguments
dynamically.
5. Syntax to create Prepared Statement object :
PreparedStatementpstmt = null;
try {
String SQL = “Update Employees SET age = ? WHERE id = ?”;
pstmt = conn.prepareStatement(SQL);

}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}
6. All parameters in JDBC are represented by the symbol, which is
known as the parameter marker. We must supply values for every
parameter before executing the SQL statement.
7. To close the Prepared Statement object a simple call to the close()
method is made. If we close the connection object first, it will close
the Prepared Statement object as well.
Stored Procedure in Java

1. A program which contains n number of SQL statements and residing a


database environment is known as stored procedure.
2. Stored procedures are divided into two types :
a. Procedure :
i. A procedure is one which contains block of statements which
will return either zero or more than one value.

ii. Syntax for creating a procedure :


create procedure <procedure name> (parameters)
as/is
local variables;
begin
block of statements;
end;

b. Function :
i. A function is one which contains n number of block of
statements to perform some operation and it returns a single
value only.
ii. Syntax for creating a function :
create function (a in number, b in number) return <return
type>
as/is
n1 out number;
begin
n1:=a+b; return (n1);
end;

Difference between Stored Procedure & Function-

S. No. Stored procedure Function


1. It is used to perfo rm It is used to perform
business logic. calculation.
2. It may or may not have the It must have the return type.
return type.
3. It may return more than It may return only one value.
one values.
4. We can call functions from Procedure cannot be called from
the procedure. function.
5. Procedure supports input Function supports only input
and output parameters. parameter.
6. Exception handling using Exception handling using try/catch
try/catch block can be used block cannot be used in user-defined
in stored procedures. functions.

Transaction Management in JDBC-


1. A transaction is a group of operation used to perform single task.
2. If all operations in the group are successful then the task is finished and
the transaction is successfully completed.
3. If any one operation in the group is failed then the task is failed and the
transaction is failed.

Types of transaction-
1. Local transaction : A local transaction means that all operations in a
transaction are executed against one database.
For example : If we transfer money from first account to second account
and both accounts belongs to same bank then transaction is local
transaction.

2. Global transaction : A global transaction means that all operations in


a transaction are executed against multiple databases.
For example : If we transfer money from first account to second account
belongs to different banks then the transaction is a global transaction.

You might also like