WEB APPLICATION AND TECHNOLOGY
ORDER & UNORDER LIST
<ol>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>
<ul>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ul>
Js for loop
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JS WHILE LOOP
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
ADDING TWO NO.
const num1 = 5;
const num2 = 3;
// add two numbers
const sum = num1 + num2;
// display the sum
console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
Largest Number Among Three Number
// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
let largest;
// check the condition
if(num1 >= num2 && num1 >= num3) {
largest = num1;
}
else if (num2 >= num1 && num2 >= num3) {
largest = num2;
}
else {
largest = num3;
}
// display the result
console.log("The largest number is " + largest);
// program to find the largest among three numbers
// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
const largest = Math.max(num1, num2, num3);
// display the result
console.log("The largest number is " + largest);
PRINT HELLO SERVLET
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
What is a Servlet?
Servlet can be described in many ways, depending on the context.
● 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.
Advantages of ServleT
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
Disadvantages of Servlet
● One servlet is loaded into JVM. ...
● When there is a request, there is a thread, not a process.
● Servlet is persistent until it destroys.
● Designing in a servlet is difficult and slows down the application.
● You need a JRE(Java Runtime Environment) on the server to run servlets.
Life Cycle of a Servlet
The entire life cycle of a Servlet is managed by the Servlet container which
uses the javax.servlet.Servlet interface to understand the Servlet object and
manage it. So, before creating a Servlet object, let’s first understand the life cycle
of the Servlet object which is actually understanding how the Servlet container
manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four
stages,
● Loading a Servlet.
● Initializing the Servlet.
● Request handling.
● Destroying the Servlet.
Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves
loading and initializing the Servlet by the Servlet container. The Web
container or Servlet Container can load the Servlet at either of the
following two stages :
○ Initializing the context, on configuring the Servlet with a zero
or positive integer value.
○ If the Servlet is not preceding stage, it may delay the loading
process until the Web container determines that this Servlet is
needed to service a request.
2. The Servlet container performs two operations in this stage :
○ Loading : Loads the Servlet class.
○ Instantiation : Creates an instance of the Servlet. To create a
new instance of the Servlet, the container uses the no-
argument constructor.
3.
4. Initializing a Servlet: After the Servlet is instantiated successfully, the
Servlet container initializes the instantiated Servlet object. The
container initializes the Servlet object by invoking the
Servlet.init(ServletConfig) method which accepts ServletConfig object
reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method
only once, immediately after the Servlet.init(ServletConfig) object is
instantiated successfully. This method is used to initialize the
resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container
by throwing the ServletException or UnavailableException.
5. Handling request: After initialization, the Servlet instance is ready to
serve the client requests. The Servlet container performs the following
operations when the Servlet instance is located to service a request :
○ It creates the ServletRequest and ServletResponse objects.
In this case, if this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse
objects which are subtypes of the ServletRequest and
ServletResponse objects respectively.
○ After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by
passing the request and response objects.
6. The service() method while processing the request may throw the
ServletException or UnavailableException or IOException.
7. Destroying a Servlet: When a Servlet container decides to destroy the
Servlet, it performs the following operations,
○ It allows all the threads currently running in the service method
of the Servlet instance to complete their jobs and get released.
○ After currently running threads have completed their jobs, the
Servlet container calls the destroy() method on the Servlet
instance.
8. After the destroy() method is executed, the Servlet container releases
all the references of this Servlet instance so that it becomes eligible for
garbage collection
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet :
● init()
● service()
● destroy()
What are Cookies?
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut
down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information
about the user":
● When a user visits a web page, his/her name can be stored in a cookie.
● Next time the user visits the page, the cookie "remembers" his/her name.
Cookies are saved in name-value pairs like:
username = John Doe
When a browser requests a web page from a server, cookies belonging to the
page are added to the request. This way the server gets the necessary data to
"remember" information about users.
Advantages of using cookies
Here are some of the advantages of using cookies to store session state.
· Cookies are simple to use and implement.
· Occupies less memory, do not require any server resources and are stored on the
user's computer so no extra burden on server.
· We can configure cookies to expire when the browser session ends (session cookies)
or they can exist for a specified length of time on the client’s computer (persistent
cookies).
· Cookies persist a much longer period of time than Session state.
Disadvantages of using cookies
Here are some of the disadvantages:
· As mentioned previously, cookies are not secure as they are stored in clear text they
may pose a possible security risk as anyone can open and tamper with cookies. You can
manually encrypt and decrypt cookies, but it requires extra coding and can affect
application performance because of the time that is required for encryption and
decryption
· Several limitations exist on the size of the cookie text(4kb in general), number of
cookies(20 per site in general), etc.
· User has the option of disabling cookies on his computer from browser’s setting .
· Cookies will not work if the security level is set to high in the browser.
· Users can delete a cookies.
· Users browser can refuse cookies,so your code has to anticipate that possibility.
· Complex type of data not allowed (e.g. dataset etc). It allows only plain text (i.e.
cookie allows only string content)
JSP
● It stands for Java Server Pages.
● It is a server side technology.
● It is used for creating web application.
● It is used to create dynamic web content.
● In this JSP tags are used to insert JAVA code into HTML pages.
● 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.
● They are easy to maintain.
● No recompilation or redeployment is required.
● JSP has access to entire API of JAVA .
● JSP are extended version of Servlet.
Advantages of using JSP
● It does not require advanced knowledge of JAVA
● It is capable of handling exceptions
● Easy to use and learn
● It can tags which are easy to use and understand
● Implicit objects are there which reduces the length of code
● It is suitable for both JAVA and non JAVA programmer
Disadvantages of using JSP
● Difficult to debug for errors.
● First time access leads to wastage of time
● It’s output is HTML which lacks features.
The Lifecycle of a JSP Page
A Java Server Page life cycle is defined as the process that started with its
creation which later translated to a servlet and afterward servlet lifecycle comes
into play. This is how the process goes on until its destruction.
Following steps are involved in the JSP life cycle:
● Translation of JSP page to Servlet
● Compilation of JSP page(Compilation of JSP into test.java)
● Classloading (test.java to test.class)
● Instantiation(Object of the generated Servlet is created)
● Initialization(jspInit() method is invoked by the container)
● Request processing(_jspService()is invoked by the container)
● JSP Cleanup (jspDestroy() method is invoked by the container)
We can override jspInit(), jspDestroy() but we can’t override _jspService()
method.
Translation of JSP page to Servlet :
This is the first step of the JSP life cycle. This translation phase deals with the
Syntactic correctness of JSP. Here test.jsp file is translated to test.java.
Compilation of JSP page :
Here the generated java servlet file (test.java) is compiled to a class file
(test.class).
Classloading :
Servlet class which has been loaded from the JSP source is now loaded into the
container.
Instantiation :
Here an instance of the class is generated. The container manages one or more
instances by providing responses to requests.
Initialization :
jspInit() method is called only once during the life cycle immediately after the
generation of Servlet instance from JSP.
Request processing :
_jspService() method is used to serve the raised requests by JSP. It takes
request and response objects as parameters. This method cannot be overridden.
JSP Cleanup :
In order to remove the JSP from the use by the container or to destroy the
method for servlets jspDestroy()method is used. This method is called once, if
you need to perform any cleanup task like closing open files, releasing database
connections jspDestroy() can be overridden.
Features of JSP
● Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
● Reduction in the length of Code :- In JSP we use action tags, custom
tags etc.
● Connection to Database is easier :-It is easier to connect website to
database and allows to read or write data easily to the database.
● Make Interactive websites :- In this we can create dynamic web pages
which helps user to interact in real time environment.
● Portable, Powerful, flexible and easy to maintain :- as these are
browser and server independent.
● No Redeployment and No Re-Compilation :- It is dynamic, secure
and platform independent so no need to re-compilation.
● Extension to Servlet :- as it has all features of servlets, implicit objects
and custom tags
Example of Hello World
We will make one .html file and .jsp file
demo.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>
Difference between Servlet and JSP
Servlet JSP
Servlet is a java code. JSP is a html based code.
Writing code for servlet is harder than JSP is easy to code as it is java in
JSP as it is html in java. html.
Servlet plays a controller role in MVC JSP is the view in MVC approach for
approach. showing output.
JSP is slower than Servlet because
the first step in JSP lifecycle is the
Servlet is faster than JSP.
translation of JSP to java code and
then compile.
Servlet can accept all protocol
JSP only accept http requests.
requests.
In Servlet, we can override the In JSP, we cannot override its
service() method. service() method.
In Servlet by default session
In JSP session management is
management is not enabled, user
automatically enabled.
have to enable it explicitly.
In Servlet we have to implement
In JSP business logic is separated
everything like business logic and
from presentation logic by using
presentation logic in just one servlet
javaBeans.
file.
Modification in Servlet is a time JSP modification is fast, just need to
consuming task because it includes
reloading, recompiling and restarting click the refresh button.
the server.
What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your
website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to
accomplish, and wraps them into methods that you can call with a single line of
code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX
calls and DOM manipulation.
The jQuery library contains the following features:
● HTML/DOM manipulation
● CSS manipulation
● HTML event methods
● Effects and animations
● AJAX
● Utilities
JQUERY HIDE/SHOW
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
JQUERY FADE
jQuery has the following fade methods:
● fadeIn()
● fadeOut()
● fadeToggle()
● fadeTo()
fadeIn()
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>
<p>Demonstrate fadeIn() with different parameters.</p>
<button>Click to fade in boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-
color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-
color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-
color:blue;"></div>
</body>
</html>
fadeOut()
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
fadeToggle()
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
fadeTo()
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
jQuery Sliding Methods
jQuery has the following slide methods:
● slideDown()
● slideUp()
● slideToggle()
slideDown()
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.mi
n.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
slideUp()
$("#flip").click(function(){
$("#panel").slideUp();
});
slideToggle()
$("#flip").click(function(){
$("#panel").slideToggle();
});
jQuery Animation
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
jQuery Stop
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
font-size: 18px;
text-align: center;
background-color: #555;
color: white;
border: solid 1px #666;
border-radius: 3px;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<button id="stop">Stop sliding</button>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
Java Remote Method Invocation
(RMI)
● The RMI stands for Remote Method Invocation is an API mechanism.
● This mechanism allows an object residing in one system (JVM) to access an
object running on another JVM.
● This mechanism generally creates distributed applications in java.
● The RMI provides remote communication between the java applications using
two objects called stub and skeleton.
The Architecture of Remote Method
Invocation (RMI)
● A remote object is an object whose method can be invoked from another JVM.
● Java RMI application contains two types of programs such as server program
and client program.
● In the server-side program, a remote object is created, and a reference of that
remote object is made available for the client-side using a registry.
● The client-side program requests the remote objects on the server and tries to
invoke its methods.
Components of RMI Architecture
Stub
● The stub is an object, acts as a gateway for the client-side.
● All the outgoing requests are routed through it.
● It resides at the client-side and represents the remote object.
● When the caller invokes a method on the stub object, it does the following tasks:
● It initiates a connection with remote Virtual Machine (JVM),
● It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
● It waits for the result
● It reads (unmarshals) the return value or exception, and
● It finally, returns the value to the caller.
Skeleton
● The skeleton is an object, acts as a gateway for the server-side object.
● All the incoming requests are routed through it. When the skeleton receives the
incoming request, it does the following tasks:
● It reads the parameter for the remote method
● It invokes the method on the actual remote object, and
● It writes and transmits (marshals) the result to the caller.
Transport Layer
● This layer connects the client and the server.
● It manages the existing connection and also sets up new connections.
● It is responsible for the transportation of data from one machine to another.
● The default connection is set up only in the TCP/IP protocol.
RRL(Remote Reference Layer)
● It is the layer that manages the references made by the client to the remote
object.
● This layer gets a stream-oriented connection from the transport layer.
● It is responsible for dealing with the semantics of remote invocations.
● It is also responsible for handling duplicated objects and for performing
implementation-specific tasks with remote objects.
Working of RMI
● When the client makes a call to the remote object, it is received by the stub which
eventually passes this request to the RRL.
● When the client-side RRL receives the request, it invokes a method called
invoke() of the object remoteRef. It passes the request to the RRL on the server-
side.
● The RRL on the server-side passes the request to the Skeleton (proxy on the
server) which finally invokes the required object on the server.
● The result is passed all the way back to the client.
Packages used in RMI
● java.rmi - Provides the RMI package.
● java.rmi.activation - Provides support for RMI Object Activation.
● java.rmi.dgc - Provides classes and interface for RMI distributed garbage-
collection (DGC).
● java.rmi.registry - Provides a class and two interfaces for the RMI registry.
● java.rmi.server - Provides classes and interfaces for supporting the server side
of RMI.
● javax.activity - Contains Activity service-related exceptions thrown by the ORB
machinery during unmarshalling.
● javax.management.remote.rmi - The RMI connector is a connector for the JMX
Remote API that uses RMI to transmit client requests to a remote MBean server.
● javax.rmi - Contains user APIs for RMI-IIOP.
● javax.rmi.CORBA - Contains portability APIs for RMI-IIOP.
● javax.transaction - Contains three exceptions thrown by the ORB machinery
during unmarshalling.
● org.omg.stub.java.rmi - Contains RMI-IIOP Stubs for the Remote types that
occur in java.rmi package.
CLIENT SERVER PROGRAM
// A Java program for a Client
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
Streams
A stream is basically a sequence of data. Whatever data we use in our programming flows through
a stream. A stream can be thought of as a channel connecting a processor or logic unit (where data
is processed according to the instructions) and input and output devices.
Input and Output Stream
If the stream acts as a source stream for the logic unit, such as data that is transferred to be
processed from an input device to the logic unit, it is known as an input stream. If the stream acts
as a destination stream for the output device (that is, the data is transferred to produce output at the
output device from the logic unit), it is known as an output stream.
AJAX
AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related
technologies like JavaScript
, DOM, XML
, HTML
/XHTML
, CSS
, XMLHttpRequest
etc.
AJAX allows you to send and receive data asynchronously without reloading the web
page. So it is fast.
AJAX allows you to send only important information to the server, not the entire page.
So only valuable data from the client side is routed to the server side. It makes your
application interactive and faster.
How Does It Work?
It creates more interactive techniques for faster and more efficient web
applications by using JavaScript, XML, CSS, and HTML. For various web
applications, Ajax uses various techniques like this.
● In Ajax, when the user needs to create content, XHTML is used while
CSS is used for presenting the user request purpose; the document
object model (DOM) and javascript both will be used to display the
content dynamically.
● By using synchronous methods in web applications, information can be
transmitted and received effectively, for example, when you fill a form
and submit it. You will be automatically directed to the new server with
that page information.
● After hitting the submit button in the background, javascript sends a
request, and with the response generated, it will update to the current
screen. In this process, the user will be unaware of the background XML
code requests.
● XML is used as a format to generate and receive the server data in any
format.
● While most web browsers are dependent on web server technology, it is
independent of web server software.
Where to Use It?
Below mentioned are the places where Ajax is used.
Login forms: Eg: user can type their login credentials in the original page form;
their software will send a request to the server to logged in, and the page will
be updated as needed.
Auto-complete: When you run a query in the Google search bar with the help
of autofill settings, suggestions will be shown in drop down below
Rating and Voting: The voting can decide the site’s main content in web pages
like Digg and Reddit by bookmarking them.
Updating with user content: When a user posts a tweet, it will be added to their
feed, and everything is updated.
Now it is used by tweeter to run their trending topics page
● Form submission and validation
● It makes web applications quicker, and the numbers of responses are
also reduced.
● Light-boxes are used nowadays instead of pop-ups
● Using Ajax with flash application
Why is Ajax Used?
Ajax is a web developer’s long term dream because the user can do the
following things:
1. Without reloading the page, the user request can be updated
2. After the page is loaded, it generates data from the server.
3. Receive data from the server after the page has loaded.
4. In the background, sends data to the server
Examples of Ajax Application
Given below are the lists of web applications that commonly use Ajax
● Google suggests that auto-complete options will be offered while typing
when a user enters the search query in the Google search bar.
Suggestions given by Google can be navigated by using operational
keys.
● Yahoo maps are easier while operating, and user experiences more fun.
This Map uses Ajax to drag the entire map with the mouse without
using buttons that will be at ease to the user.
● Google maps are general applications that use Ajax. This is a real-time
application in which the user can manipulate the data and change the
view settings. Ajax directly works on a web browser without any plugin
installations. Firstly, only Microsoft internet explorer used Ajax, but due
to its reliability, more web applications like chrome, Mozilla… Etc. using
this.
Ajax applications use an intermediate engine that acts as a bridge between
browser and server. Ajax is not a programming language.
Advantages and Disadvantages of Ajax
Every software has its pros and cons, which gives good results when handled
in a correct way.
Advantages
● Reduces the server traffic and increases the speed
● It is responsive, and the time taken is also less
● Form validation
● Bandwidth usage can be reduced
● Asynchronous calls can be made; this reduces the time for data arrival.
Disadvantages
● Open-source
● Active x request is created only in internet explorer and a newly created
web browser.
● For security reasons, you can only access information from the web
host that serves pages. Fetching information from other servers is not
possible with Ajax.
JavaScript jQuery
JavaScript uses JIT[Just in Time While JQuery Uses the
Compiler] which is a combination resources that are provided
1 of interpreter and Compile and is by JavaScript to make things
. written in C. It’s a combination of easier. It is a lightweight
ECMAscript and DOM JavaScript library. It has only
(Document Object Model). the DOM.
2 JavaScript uses long lines of With JQuery, one has to write
. code as an individual has to write fewer lines of code than
the code own-self. JavaScript. We just need to
import the library and use the
only specific functions or
methods of the library in our
code.
JQuery has an inbuilt feature
of cross-browser
compatibility. We don’t need
In JavaScript, we have to write
3 to worry about writing extra
extra code or move around to
. lines of code or moving
have cross-browser compatibility.
around in order to make our
code compatible with any
browser.
Unlike JavaScript, JQuery is
JavaScript can be a burden over
more user-friendly; only a few
4 a developer as it may take a
lines of code have to be
. number of lines of lengthy code
written in order to have its
to attain functionality.
functionality.
JavaScript is verbose because
JQuery is concise and one
5 one has to write their own
need not write much as
. scripting code which is time-
scripting already exists.
consuming.
Pure JavaScript can be faster for
JQuery is also fast with
DOM selection/manipulation than
modern browsers and modern
6 jQuery as JavaScript is directly
computers. JQuery has to be
. processed by the browser and it
converted into JavaScript to
curtails the overhead which
make it run in a browser.
JQuery actually has.
We can make animations in
JavaScript with many lines of In JQuery, we can add
7 code. Animations are mainly animation effects easily with
. done by manipulating the style of fewer lines of code.
an Html page.
8 JavaScript is a language, While JQuery is a library,
. obviously, it would be heavier derived from JavaScript
than JQuery. hence, it is lightweight.
JQuery is a JavaScript library.
It would not have been
invented had JavaScript not
JavaScript is an independent there. jQuery is still
9 language and can exist on its dependent on JavaScript as it
. own. has to be converted to
JavaScript for the browser in-
built JavaScript engine to
interpret and run it
What is a TCP/IP Socket Connection ?
A socket programming interface provides the routines required for interprocess
communication between applications, either on the local system or spread in a
distributed, TCP/IP based network environment. Once a peer-to-peer connection is
established, a socket descriptor is used to uniquely identify the connection. The socket
descriptor itself is a task specific numerical value.
One end of a peer-to-peer connection of a TCP/IP based distributed network application
described by a socket is uniquely defined by
● Internet address
for example 127.0.0.1 (in an IPv4 network) or FF01::101 (in an IPv6 network).
● Communication protocol
○ User Datagram Protocol (UDP)
○ Transmission Control Protocol (TCP)
● Port
A numerical value, identifying an application. We distinguish between
○ "well known" ports, for example port 23 for Telnet
○ user defined ports
Socket applications were usually C or C++ applications using a variation of the socket
API originally defined by the Berkeley Software Distribution (BSD). The JAVA language
also provides a socket API. JAVA based Client/Server applications exploit those socket
services.
Socket programming interfaces have been standardized for ease of portability by The
Open Group for example.
Besides TCP/IP based sockets, UNIX systems provide socket interfaces for
interprocess communication (IPC) within the local UNIX host itself. Those UNIX sockets
use the local file system for interprocess communication.
z/VSE provides TCP/IP based socket services. They can be used for IPC too, although
they are primarily aimed for network communication only.
What is UDP socket programming?
Description. UDP socket routines enable simple IP communication using the user
datagram protocol (UDP). The User Datagram Protocol (UDP) runs on top of the
Internet Protocol (IP) and was developed for applications that do not require reliability,
acknowledgment, or flow control features at the transport layer.
JSP Implicit Objects
There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1) JSP out implicit object
For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write:
10 Sec
26.1M
446
Hello Java Program for Beginners
1. PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code.
Example of out implicit object
In this example we are simply displaying date and time.
index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output
What are JSP Directives?
● JSP directives are the messages to the JSP container. They provide
global information about an entire JSP page.
● JSP directives are used to give special instruction to a container for
translation of JSP to servlet code.
● In the JSP life cycle phase, JSP has to be converted to a servlet which
is the translation phase.
● They give instructions to the container on how to handle certain aspects
of JSP processing
● Directives can have many attributes by comma separated as key-value
pairs.
● In JSP, directive is described in <%@ %> tags.
Syntax of Directive:
<%@ directive attribute="" %>
There are three types of directives:
1. Page directive
2. Include directive
3. Taglib directive
Attributes of JSP page directive
● import
● contentType
● extends
● info
● buffer
● language
● isELIgnored
● isThreadSafe
● autoFlush
● session
● pageEncoding
● errorPage
● isErrorPage
What is the autoFlush attribute in JSP?
The autoFlush attribute specifies whether the buffered output should be flushed
automatically when the buffer is filled, or whether an exception should be raised to
indicate the buffer overflow.
A value of true (default) indicates automatic buffer flushing and a value of false throws
an exception.
Example:
welcome.jsp
<%@ page autoFlush="true" %>
<html>
<head>
<title>autoFlush page directive example</title>
</head>
<body>
<h3>Hello this is a autoFlush page directive
example.</h3>
</body>
</html>
web.xml
<web-app>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
AJAX: Synchronous or Asynchronous
AJAX can access the server both synchronously and asynchronously:
Synchronously, in which the script stops and waits for the server
to send back a reply before continuing.
Asynchronously, in which the script allows the page to continue to
be processed and handles the reply if and when it arrives.
Synchronous Ajax requests: In this, the script stops and waits for the server to
reply before continuing. In the web application world, one has to happen after the
other, i.e. the interaction between the customer and the server is synchronous.
Synchronous is not recommended as it blocks/hangs the page until the response
is received from the server.
Asynchronous Ajax requests handle the reply as and when it comes and allows
the page to continue to be processed. Under Asynchronous, if there is any
problem in the request it can be modified and recovered. The request doesn’t
block the client as the browser is responsive. The user can perform other
operations as well.
What Does Marshalling Mean?
Marshalling is the process of transforming the memory representation of an
object into another format, which is suitable for storage or transmission to
other software applications. Marshalling allows communication between
remote objects by converting an object into serialized form.
“Unmarshalling” is the process of converting some kind of a lower-level representation,
often a “wire format”, into a higher-level (object) structure.
Sender-Receiver Interface
A sender-receiver (S/R) interface is a special kind of port-interface used for the case of
sender-receiver communication. The sender-receiver interface defines the data-elements
which are sent by a sending component (which has a p-port providing the sender-receiver
interface) or received by a receiving component (which has an r-port requiring the sender-
receiver interface).
Sender-Receiver interfaces are used for data exchange between software components. The
interface specifies which data is transferred from the sender to the receiver. It is composed
of variable data prototypes and specifies the transferred data. The variable data prototypes
are of a type which describes the possible values of a variable on physical and internal
level. The internal values of the Data Type can be converted to physical values via a compu
method. The range of the values can be restricted with data constr elements.
Client-Server Interface
The client-server interface is a special kind of port-interface used for the case of Client-
Server Communication. The client-server interface defines the operations that are provided
(implemented) by the server and that can be used by the client. Client-server interfaces
allow a client to call an operation at a server, which in turn provides the result to the client.
The argument data prototypes of the operation of an interface can be the client input to the
server (IN) or the server result (OUT) or both (INOUT).
The ServerRef Interface
The interface ServerRef represents the server-side handle for a remote object
implementation.
package java.rmi.server;
public interface ServerRef extends RemoteRef {
RemoteStub exportObject(java.rmi.Remote obj, Object data)
throws java.rmi.RemoteException;
String getClientHost() throws ServerNotActiveException;
}
The method exportObject finds or creates a client stub object for the supplied Remote
object implementation obj.The parameter data contains information necessary to export the
object (such as port number).
The method getClientHost returns the host name of the current client. When called from a
thread actively handling a remote method invocation, the host name of the client invoking
the call is returned. If a remote method call is not currently being service, then
ServerNotActiveException is called.
The Skeleton Interface
The interface Skeleton is used solely by the implementation of skeletons generated by
the rmic compiler. A skeleton for a remote object is a server-side entity that dispatches
calls to the actual remote object implementation.
package java.rmi.server;
public interface Skeleton {
void dispatch(Remote obj, RemoteCall call, int opnum, long hash)
throws Exception;
Operation[] getOperations();
}
The dispatch method unmarshals any arguments from the input stream obtained from
the call object, invokes the method (indicated by the operation number opnum) on the
actual remote object implementation obj, and marshals the return value or throws an
exception if one occurs during the invocation.
The getOperations method returns an array containing the operation descriptors for the
remote object's methods.
JSP Scriptlet tag (Scripting elements)
1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see
what are the scripting elements first.
JSP Scripting elements
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 scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1. <% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
Java Try Catch
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The index.html
file gets the username from the user and the welcome.jsp file prints the username with
the welcome message.
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JavaBean
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.
Simple example of JavaBean class
1. //Employee.java
2.
3. package mypack;
4. public class Employee implements java.io.Serializable{
5. private int id;
6. private String name;
7. public Employee(){}
8. public void setId(int id){this.id=id;}
9. public int getId(){return id;}
10. public void setName(String name){this.name=name;}
11. public String getName(){return name;}
12. }
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4. Employee e=new Employee();//object is created
5. e.setName("Arjun");//setting value to the object
6. System.out.println(e.getName());
7. }}
Note: There are two ways to provide values to the object. One way is by constructor and
second is by setter method.
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.
Prime Ministers of India | List of Prime Minister of India (1947-2020)
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.
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.
What is JavaBeans in JSP?
Bean means component. Components mean reusable objects. JavaBean is a reusable
component. Java Bean is a normal java class that may declare properties, setter, and getter
methods in order to represent a particular user form on the server-side. JavaBean is a java
class that is developed with a set of conventions. The conventions are:
1. The class should be public and must not be final, abstract.
2. Recommend to implement serializable.
3. Must have direct/indirect param constructor.
4. Member variables should be non-static and private.
5. Every bean property should have one setter method and one getter method
with the public modifier.
Note: setter method is useful to set data to bean property whereas the getter method is
useful to read data from bean property.
Java Bean is useful to combine multiple simple values to an object and to send that object
from one resource to another resource or one layer to another layer. For example, to keep
form data into a single object we can use java bean. Java Bean is a specially constructed
Java class written in Java and coded according to the Java Beans API specification.
Why do we need to use JavaBeans in JSP?
1. It provides a default, no-argument constructor.
2. It should be serializable and implement the Serializable interface.
3. It may have a number of properties/variables which can be read or written.
4. It may have a number of “getter” and “setter” methods for the properties.
Working of JavaBeans in JSP
First, the browser sends the request for the JSP page. Then the JSP page accesses Java
Bean and invokes the business logic. After invoking the business logic Java Bean connects
to the database and gets/saves the data. At last, the response is sent to the browser which
is generated by the JSP.
Advantages of Java Beans
1. It is easy to reuse the software components.
2. The properties and methods of Java Bean can be exposed to another
application.
Disadvantages of Java Beans
1. JavaBeans are mutable objects so it cannot take advantage of immutable
objects.
2. JavaBeans will be in an inconsistent state because of creating the setter and
getter method for each property separately.
Java Bean Properties
1. getPropertyName(): This method is used to read the property which is also
called accessor.
2. setPropertyName(): This method is used to write the property which is also
called mutator.
How to access JavaBeans in JSP Application?
<jsp:useBean>
The jsp:useBean tag is utilized to start up an object of JavaBean or it can re-utilize the
existing java bean object. The primary motivation behind jsp:useBean tag is to interface with
bean objects from a specific JSP page. In this tag, it is consistently suggestible to give
either application or meeting degree to the extension characteristic worth. At the point when
the compartment experiences this label then the holder will get class characteristic worth for
example completely qualified name of Bean class then the holder will perceive Bean .class
record and perform Bean class stacking and launch. Subsequent to making the Bean object
compartment will allot Bean object reference to the variable indicated as an incentive to id
property. In the wake of getting Bean object reference holder will store Bean object in an
extension indicated as an incentive to scope trait.
Syntax: <jsp:useBean id=”—” class”—” type”—” scope=”—”/>
Attributes:
1. Id: It will take a variable to manage generated Bean object reference.
2. Class: This attribute will take the fully qualified name of the Bean class.
3. Type: It will take the fully qualified name of the Bean class to define the type
of variable in order to manage the Bean object reference.
4. Scope: It will take either of the JSP scopes to the Bean object.
<jsp:getProperty>
The jsp:getProperty tag is utilized to get indicated property from the JavaBean object. The
principle reason for <jsp:getProperty> tag is to execute a getter strategy to get an incentive
from the Bean object.
Syntax: <jsp:getProperty name=”—” property=”—”/>
Attributes:
1. Name: It will take a variable that is the same as the id attribute value in
<jsp:useBean> tag.
2. Property: It will take a particular property to execute the respective getter
method.
<jsp:setProperty>
The jsp:setProperty tag is utilized to set a property in the JavaBean object. The principle
motivation behind jsp:setProperty tag is to execute a specific setter technique to set an
incentive to a specific Bean property.
Syntax: <jsp:setProperty name=”—” property=”—” value=”—”/>
Attributes:
1. Name: It will take a variable that is the same as the id attribute value in
<jsp:useBean> tag.
2. Property: It will take a property name in order to access the respective setter
method.
3. Value: It will take a value to pass as a parameter to the respective setter
method.
JSP JavaBeans Example
In this example, we have created a Simple Bean class Test.java and index.jsp page which
loads the bean and sets/gets a simple String Parameter.
Test.java
package Action;
public class Test {
private String message = "No message specified";
public String getMessage() {
return (message);
}
public void setMessage(String message) {
this.message = message;
}
}
Index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="Action.Test" />
<jsp:setProperty name="test" property="message" value="Hello
JSP..." />
<p>Got message....</p>
<jsp:getProperty name="test" property="message" />
</body>
</html>
how will you use jsp with another language???
Try catch in JSP
In try block we write those code which can throw exception while code execution and
when the exception is thrown it is caught inside the catch block. The try catch block in
jsp just work as try catch block in the java.
The code of the program is given below:
<HTML>
<HEAD>
<TITLE> Use of Try catch in jsp</TITLE>
</HEAD>
<BODY>
<table align="center" bgcolor="#E1E1FF" border="1">
<H1>Use of Try catch in jsp</H1>
<%
try{
int a = 10;
int b = 10;
b = a / 0;
}
catch(Exception e){
out.println("The Error is: " + e);
}
%>
</table>
</BODY>
</HTML>
jsp:setProperty and jsp:getProperty
action tags
The setProperty and getProperty action tags are used for
developing web applications with Java Bean. In web development,
bean class is mostly used because it is a reusable software
component that represents data.
The jsp:setProperty action tag sets a property value or values in a
bean using the setter method.
Syntax of jsp:setProperty action tag
1. <jsp:setProperty name="instanceOfBean" property= "*" |
2. property="propertyName" param="parameterName" |
3. property="propertyName" value="{ string | <%= expression
%>}"
4. />
Example of jsp:setProperty action tag if you have to set all the
values of incoming request in the bean
1. <jsp:setProperty name="bean" property="*" />
Example of jsp:setProperty action tag if you have to set value
of the incoming specific property
1. <jsp:setProperty name="bean" property="username" />
Example of jsp:setProperty action tag if you have to set a
specific value in the property
1. <jsp:setProperty name="bean" property="username"
value="Kumar" />
jsp:getProperty action tag
The jsp:getProperty action tag returns the value of the property.
Syntax of jsp:getProperty action tag
1. <jsp:getProperty name="instanceOfBean"
property="propertyName" />
Simple example of jsp:getProperty action tag
1. <jsp:getProperty name="obj" property="name" />
Example of bean development in JSP
In this example there are 3 pages:
● index.html for input of values
● welocme.jsp file that sets the incoming values to the bean
object and prints the one value
● User.java bean class that have setter and getter methods
index.html
1. <form action="process.jsp" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. Email:<input type="text" name="email"><br>
5. <input type="submit" value="register">
6. </form>
process.jsp
1. <jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
2. <jsp:setProperty property="*" name="u"/>
3.
4. Record:<br>
5. <jsp:getProperty property="name" name="u"/><br>
6. <jsp:getProperty property="password" name="u"/><br>
7. <jsp:getProperty property="email" name="u" /><br>
User.java
1. package org.sssit;
2.
3. public class User {
4. private String name,password,email;
5. //setters and getters
6. }