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

Web Technology

web tech

Uploaded by

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

Web Technology

web tech

Uploaded by

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

WEB TECHNOLOGY

What is web 2.0?


The second stage of development of internet, characterized by more user
generated content.
Keys:-
1. Basic web technology terms
2. HTML vs XHTML
3. Javascript-DOM(Document Object Model)
4. JSP (Java Server Page)
1. Basic web technology terms
 Internet
 Network
 Web page
 Web browser
 Search engine
 Url
 Web server
 Protocols
 E_mail

What is XHTML
XHTML stands for EXtensible HyperText Markup Language. It is a cross between HTML
and XML language.

XHTML is almost identical to HTML but it is stricter than HTML. XHTML is HTML defined
as an XML application. It is supported by all major browsers.
Difference between HTML and XHTML

HTML XHTML

HTML stands for Hypertext XHTML stands for Extensible


Markup Language. Hypertext Markup Language.

It was developed by Tim It was developed by W3C i.e


Berners-Lee. World Wide Web Consortium.

It was developed in 1991. It was released in 2000.

It is extended from XML and


It is extended from SGML.
HTML.

The format is a document file


The format is a markup language.
format.

All tags and attributes are not


In this, every tag and attribute
necessarily to be in lower or
should be in lower case.
upper case.

Doctype is not necessary to write Doctype is very necessary to


at the top. write at the top of the file.
HTML XHTML

It is not necessary to close the


It is necessary to close the tags in
tags in the order they are
the order they are opened.
opened.

While using the attributes it is While using the attributes it is


not necessary to mention mandatory to mention
quotes. For e.g. <id>. quotes. For e.g. <class=”GFG”>.

Filename extension used are Filename extension are .xhtml,


.html, .htm. .xht, .xml.

Introduction to XML
XML is a software- and hardware-independent tool for storing and
transporting data in structured form.

What is XML?
 XML stands for eXtensible Markup Language
 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive
 XML is a W3C Recommendation

XML Document Structure


1. An XML declaration
2. A document type declaration that refers to a DTD
3. A body or document instance

1. An XML declaration

<?xml version="1.0" ?>

2. A DTD

<!DOCTYPE RootElement (SYSTEM | PUBLIC)

ExternalDeclarations? [InternalDeclarations]? >

3. A body or document instance

Simple XHTML 1.0 Document with XML Prolog and Document Body

PROGRAMMING WITH JAVA SCRIPT- DOM AND EVENTS

JavaScript can access all the elements in a webpage making


use of Document Object Model (DOM). In fact, the web
browser creates a DOM of the webpage when the page is
loaded. The DOM model is created as a tree of objects like
this:
Finding HTML Elements
There are several ways to do this:

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name

 Finding HTML elements by CSS selectors


 Finding HTML elements by HTML object collections
Traversing and Modifying a DOM Tree

Traversing and modifying a DOM tree means moving up, down, and
sideways through the DOM tree, selecting nodes based on their
relationship to other nodes.

JavaScript provides several methods to traverse the DOM.

 parentNode
 childNodes[nodenumber]
 firstChild
 lastChild
 nextSibling
 previousSibling

parentNode

In JavaScript, a parent node refers to the node that is immediately higher in the
DOM (Document Object Model) hierarchy relative to another node.
For example, consider the following HTML code:

<div>

<h2>Sample Title</h2>

<p>This is Paragraph</p>

</div>

In this code, the parent node is the div element, which contains two child nodes,
both of which are h2 and p elements.

For example, to access the parent node of the second child p element in the
example above, you could use the following code:

<script>

const para = document.getElementsByTagName("p");

document.write(para);

const parent = para[0].parentNode;

console.log(parent);

parent.style.backgroundColor = "red";

parent.style.padding = "10px";

</script>

Modifying a DOM
Adding and Removing Nodes (HTML Elements)
Append method is used to add new HTML elements.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Add a new HTML Element.</p>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
To remove an HTML element, use the remove() method:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<h3>Remove an HTML Element.</h3>
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<button onclick="myFunction()">Remove Element</button>
<script>
function myFunction() {
document.getElementById("p1").remove();
}
</script>
</body>
</html>
DOM collections and styles
The length property defines the number of elements in an HTMLCollection.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
const myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = "This document contains " + my
Collection.length + " paragraphs.";
</script>
</body>
</html>
Example :- write a javascript program to change the text color of all elem
ents.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p>Click the button to change the color of all p elements.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
}
</script>
</body>
</html>

Dom events
A JavaScript can be executed when an event occurs, like when a user clicks on an H
TML element.
Examples of HTML DOM events:

onclick() :-When a user clicks the mouse.

For example, the content of the <h1> element is changed when a user clicks on
it:

<!DOCTYPE html>
<html>
<body>

<h1 onclick="this.innerHTML = 'welcome sir'">hello sir</h1>

</body>
</html>
#Java script events handler
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<h2 onclick="changeText(this)">hello sir</h2>
<script>
function changeText(id) {
id.innerHTML = "welcome sir";
}
</script>
</body>
</html>

The onload and onunload Events:-The onload and onunload events are
triggered when the user enters or leaves the page.

The onload event can be used to check the visitor's browser type and browser
version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.

For example:-

<!DOCTYPE html>

<html>

<body onload="checkCookies()">

<h1>JavaScript HTML Events</h1>

<h2>The onload Attribute</h2>

<p id="demo"></p>

<script>

function checkCookies() {

let text = "";

if (navigator.cookieEnabled == true) {

text = "Cookies are enabled.";

} else {

text = "Cookies are not enabled.";

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

Note:-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.

The oninput Event:-The oninput event is often to some action while the
user input data.

Example-
<!DOCTYPE>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The oninput Attribute</h2>

Enter your name: <input type="text" id="fname" oninput="upperCase()">

<p>When you write in the input field, a function is triggered to transform


the input to upper case.</p>

<script>

function upperCase() {

const x = document.getElementById("fname");

x.value = x.value.toUpperCase();

</script>

</body>

</html>

The onchange Event


The onchange event is often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will be
called when a user changes the content of an input field.

<!DOCTYPE html>

<html>

<body>
<h1>JavaScript HTML Events</h1>

<h2>The onchange Attribute</h2>

Enter your name: <input type="text" id="fname"


onchange="upperCase()">

<p>When you leave the input field, a function transforms the


input to upper case.</p>

<script>

function upperCase() {

const x = document.getElementById("fname");

x.value = x.value.toUpperCase();

</script>

</body>

</html>

The onmouseover and onmouseout Events


The onmouseover and onmouseout events can be used to trigger a function when the
user mouses over, or out of, an HTML element:

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The onmouseover Attribute</h2>


<div onmouseover="mOver(this)" onmouseout="mOut(this)"

style="background-
color:#D94A38;width:120px;height:20px;padding:40px;">

Mouse Over Me</div>

<script>

function mOver(obj) {

obj.innerHTML = "Thank You"

function mOut(obj) {

obj.innerHTML = "Mouse Over Me"

</script>

</body>

</html>

The onmousedown, onmouseup and onclick Events


The onmousedown, onmouseup, and onclick events are all parts of a mouse-click.
First when a mouse-button is clicked, the onmousedown event is triggered, then,
when the mouse-button is released, the onmouseup event is triggered, finally,
when the mouse-click is completed, the onclick event is triggered

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>


<h2>The onmousedown Attribute</h2>

<div onmousedown="mDown(this)" onmouseup="mUp(this)"

style="background-
color:#D94A38;width:90px;height:20px;padding:40px;">

Click Me</div>

<script>

function mDown(obj) {

obj.style.backgroundColor = "#1ec5e5";

obj.innerHTML = "Release Me";

function mUp(obj) {

obj.style.backgroundColor="#D94A38";

obj.innerHTML="Thank You";

</script>

</body>

</html>

Introduction to AJAX

What is AJAX?
AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.


AJAX just uses a combination of:

 A browser built-in XMLHttpRequest object (to request data from a web


server)
 JavaScript and HTML DOM (to display or use the data)

Example of AJAX

<html>

<body>

<div id="demo">

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Change


Content</button>
</div>

<script>

function loadDoc() {

let xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {

document.getElementById("demo").innerHTML =

this.responseText;

};

xhttp.open("GET", "ajax_info.txt", true);

xhttp.send();

</script>

</body>

</html>

XMLHttpRequest Object Methods


Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request


getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

send() Sends the request to the server


Used for GET requests

send(string) Sends the request to the server.


Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties


Property Description

onreadystatechange Defines a function to be called when the readyState property


changes

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data


Status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

The server side scripting vs The Client-side scripting :

The server side scripting

Server-side scripts are programs that run on a web server to generate dynamic
web pages, creating a unique experience for each user. These scripts form the
basic framework for back-end web development.

The Client-side scripting :


Web browsers execute client-side scripting. It is used when browsers have all
code. Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.

Software architecture layers


Software architecture consists of

1. Tier-1

2. Tier -2

3. Tier -3
4. N -tier

A tier can also be referred as layer

Three layers involved in the application:-

Presentation layer, application layer and data layer

Presentation layer is also known as client layer. Top most layer of an


application. This is the layer we see when we use a software. By using this
layer we can access the web pages. The main functionality of this layer is to
communicate with application layer. This layer passes the information which
is given by the user in terms of keyboard actions, mouse click to the
application layer.

For example login page of Gmail.

Application layer:- application layer is also known as business logic layer


which is also known as logical layer.as per the Gmail login page example,
once user clicks on the login button, application layer interact with the
database layer and sends required information to the presentation layer. It
controls an application functionality by performing detailed processing. This
layer acts as mediator between the presentation and the database layer.

Complete business logic will be written in this layer.

Data layer: the data stored in data layer. Application layer communicates
with database layer to retrieve the data. It contains the methods that connect
the database and performs required action.

Example:- insert, update and delete.

Types of software architecture


1. Tier-1

2. Tier -2

3. Tier -3

4. N -tier

1. Tier-1:-
In 1-Tier Architecture the database is directly available to
the user, the user can directly sit on the DBMS and use it
that is, the client, server, and Database are all present on
the same machine. For Example: to learn SQL we set up an
SQL server and the database on the local system. This
enables us to directly interact with the relational database
and execute operations.

2. Tier -2:-
The 2-tier architecture is similar to a basic client-server
model. The application at the client end directly
communicates with the database on the server side. APIs
like ODBC and JDBC are used for this interaction.

3. Tier -3:-

In 3-Tier Architecture, there is another layer between the


client and the server. The client does not directly
communicate with the server. Instead, it interacts with an
application server which further communicates with the
database system and then the query processing and
transaction management takes place. This intermediate
layer acts as a medium for the exchange of partially
processed data between the server and the client. This type
of architecture is used in the case of large web applications.

4. N – tier:
An N-Tier Application program is one that is distributed among three
or more separate computers in a distributed network.

The most common form of n-tier is the 3-tier Application, and it is


classified into three categories.

 User interface programming in the user’s computer


 Business logic in a more centralized computer, and
 Required data in a computer that manages a database.
Various languages/technologies for server scripting

 Net.Data
Net.Data is a server-side scripting engine that allows you to easily create dynamic documents using live
data from a variety of sources such as relational and non-relational database management systems
(DBMSs), including DB2® databases that can be accessed through DRDA, files, and native applications
written in programming languages such as RPG, Cobol, Java™, C, C++, and REXX.
 Node.js
Node.js is an open source project based on the Google Chrome JavaScript Engine. It provides a platform
for server-side JavaScript applications running without browsers.
 PHP
Hypertext Preprocessor (PHP) is one of the world's most popular server-side scripting language for
building dynamic, data-driven Web applications.
 Python
Python is an agile, dynamically typed, expressive, open source programming language that supports
multiple programming philosophies, including procedural, object-oriented, and functional.

 HTTP request methods


Get :- The GET method requests a representation of the specified resource. Requests
using GET should only retrieve data.

Head :- The HEAD method asks for a response identical to a GET request, but without
the response body.

Post :- The POST method submits an entity to the specified resource, often causing a
change in state or side effects on the server.

Jsp application development

Introduction to JDBC

JDJDBC stands for java “database connectivity” .It is an API that is used to
connect and execute the queries with the respective database.
Example :-

Class jdbc

public static void main(String arg[])

System.out.println(“hello world”); Database

Note:- requirement to perform jdbc.

(1)JDK

(2)Eclipse IDE

(3)oracle 11g

(4) .jar file

JSP-BASICS

In Java, JSP stands for Java Server Pages. It is a server-side


technology which is used for creating web applications. It is
used to create dynamic web content. JSP consists of both
HTML tags and JSP tags. In this, JSP tags are used to insert
JAVA code into HTML pages. It is an advanced version
of Servlet Technology i.e. a web-based technology that 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 a servlet by the JSP
container before processing the client’s request. JSP has
various features like JSP Expressions, JSP tags, JSP
Expression Language, etc.

Basic JSP Life-cycle


Following steps are involved in the JSP life cycle:

1. Translation of JSP page to Servlet


2. Compilation of JSP page(Compilation of JSP into test.java)
3. Classloading (test.java to test.class)
4. Instantiation(Object of the generated Servlet is created)
5. Initialization(jspInit() method is invoked by the container)
6. Request processing(_jspService()is invoked by the container)
7. JSP Cleanup (jspDestroy() method is invoked by the container)

Servlet:- Servlets are the Java programs that run on the


Java-enabled web server or application server. They are
used to handle the request obtained from the web server,
process the request, produce the response, and then send a
response back to the web server.
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive


1. <%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive


1. <%@ page attribute="value" %>
Attributes of JSP page directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage
1)import
The import attribute is used to import class,interface or all the members of a package.It is similar to import keywo
in java class or interface.

Example of import attribute


1. <html>
2. <body>
3.
4.
5.
6. </body>
7. </html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type
of the HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute


1. <html>
2. <body>
3.
4. <%@ page contentType=application/msword %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp file,
html file or text file. The include directive includes the original content of the included
resource at page translation time (the jsp page is translated only once so it will be better
to include static resource).

Syntax of include directive


1. <%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the header.html file. To run this example
you must create an header.html file.

1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>

JSP Taglib directive


The JSP taglib directive is used to define a tag library that defines many tags. We use the
TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive


In this example, we are using our tag named currentDate. To use this tag we must specify
the taglib directive so the container may get information about the tag.

1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.google.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
Jsp elements

JSP Scripting Elements


In web applications, JSP Scripting Elements are often wont to provide code in JSP pages. All
the JSP Scripting Elements are going to be resolved at the time of request processing. The
majority of Scripting Elements will give a direct effect on response generation. JSP scripting
elements enable you to insert java code directly into the servlet that will be generated from
the current JSP page.
There are three types of Scripting Elements:
1. Declarations: Declaration of the form that is inserted into the body of the servlet class,
outside of any existing methods.
2. Scriptlets: Scriptlets of the form that are inserted into the servlets service method.
3. Expressions: Expressions of the form that are evaluated and inserted into out.

1. JSP Declarations:- A declaration can consist of either method declarations or


variables, static constants are a good example of what to put in a declaration.
When you write a declaration during a JSP page, remember these rules:

1. Must end the declaration with a semicolon.


2. <% int i=0;%>
3. We can use variables or methods that are declared in packages imported by the page
directive, without declaring them in a declaration element.
4. We can declare any number of variables or methods within one declaration element,
as long as you end each declaration with a semicolon. The declaration must be valid
in the Java programming language.
If we offer any java declarations by using-declaration scripting element then that each one
java declarations are going to be available to the translated servlet as class-level declarations.
Example:-
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Declaration</title>
</head>
<body>
<h3>--Welcome--</h3>
<h3>Use of Declaration in JSP</h3>
<%!int num1 = 2, num2 = 3, n = 0;%>
<%
n = num1 + num2 + 1;
out.println("The number after adding declared variables is " + n);
%>
</body>
</html>
JSP Scriptlets
This scripting element is often wont to provide a block of java code. It can contain any number
of language statements, variable or method declarations, or expressions that are valid within
the page scripting language. Within a scriptlet, you can do the following:
1. On the JSP page declare variables or methods to use later.
2. Write valid expressions in the page scripting language.
3. Use any of the implicit objects or any object declared with the element.
4. On the JSP page, write any other statement valid in the scripting language used.
5. All text, HTML tags, or JSP elements you write must be outside the scriptlet.

JSP Scriptlets Example:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<html>

<head>
<title>Scriptlets</title>

</head>

<body>

<h3>--Welcome--</h3>

<h3>Use of scriptlet in JSP</h3>

<%

int a = 3;

int b = 4;

int c = 5;

out.println("a is: " + a + "<br>" + "b is:" + b + "<br>" + "c is:" + c + "<br>");

out.println("Multiplication gives: " + a * b * c + "<br>");

out.println("Addition gives:" + (a + b + c));

%>

</body>

</html>
JSP Expressions
This is scripting element are often wont to evaluate the only java expression and display that
expression resultant value onto the client browser.
Syntax: <%=Java Expression%>

JSP Expressions Example:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<html>

<body>

Current Time:

<%=java.util.Calendar.getInstance().getTime()%>

</body>
</html>

Jsp variables
JSP Declaration Tag
The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of
auto generated servlet.

Syntax of JSP declaration tag

1. <%! field or method declaration %>


Difference between JSP Scriptlet tag and
Declaration tag
Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well
not methods. as methods.

The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of
the declared field using the jsp expression tag.

index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
Example of JSP declaration tag that declares method
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
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:
PrintWriter out=response.getWriter();
Example of out implicit object
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>

6. JSP request implicit object


The JSP request is an implicit object of type HttpServletRequest i.e. created for
each jsp request by the web container. It can be used to get request information
such as parameter, header information, remote address, server name, server port,
content type, character encoding etc.

Example of JSP request implicit object


index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>

3) JSP response implicit object


In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.

Example of response implicit object


index.html

1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp

1. <%
2. response.sendRedirect("http://www.google.com");
3. %>

4. session implicit object


In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to
set,get or remove attribute or to get session information.
Example of session implicit object
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>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>

11. JSP application implicit object


In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.

Example of application implicit object:


index.html

1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. <context-param>
14. <param-name>dname</param-name>
15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
16. </context-param>
17.
18. </web-app>
welcome.jsp
1. <%
2.
3. out.print("Welcome "+request.getParameter("uname"));
4.
5. String driver=application.getInitParameter("dname");
6. out.print("driver name is="+driver);
7.
8. %>

Exception Handling in JSP


Exception Handling is the process to handle the runtime errors.
In JSP, there are two ways to perform exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file
1. By errorPage and isErrorPage attributes of page directive
Example:- There are 3 files:

o index.jsp for input values


o process.jsp for dividing the two numbers and displaying the result
o error.jsp for handling the exception

index.jsp

<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No2:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

process.jsp

<%@ page errorPage="error.jsp" %>


<%

String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);

%>

error.jsp

<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>


3. By <error-page> element in web.xml file

There are 4 files:

o web.xml file for specifying the error-page element


o index.jsp for input values
o process.jsp for dividing the two numbers and displaying the result
o error.jsp for displaying the exception

web.xml file if you want to handle any exception

<web-app>

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>

</web-app>

web.xml file if you want to handle the exception for a specific error code

<web-app>

<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>

</web-app>

index.jsp file is same as in the above example

process.jsp

Now, you don't need to specify the errorPage attribute of page directive in the jsp page.

1. <%@ page errorPage="error.jsp" %>


2. <%
3.
4. String num1=request.getParameter("n1");
5. String num2=request.getParameter("n2");
6.
7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);
9. int c=a/b;
10. out.print("division of numbers is: "+c);
11.
12. %>

4) error.jsp file is same as in the above example

JSP - Sending Email


o send an email using a JSP, you should have the JavaMail API and
the Java Activation Framework (JAF) installed on your machine.

 You can download the latest version of JavaMail (Version


1.2) from the Java's standard website.
 You can download the latest version of JavaBeans Activation
Framework JAF (Version 1.0.2) from the Java's standard
website.

Download and unzip these files, in the newly-created top-level


directories. You will find a number of jar files for both the
applications. You need to add the mail.jar and the activation.jar files in
your CLASSPATH.
Send a Simple Email

Here is an example to send a simple email from your machine. It is


assumed that your localhost is connected to the Internet and that it
is capable enough to send an email. Make sure all the jar files from
the Java Email API package and the JAF package are available in
CLASSPATH.

<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>


<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<%
String result;

// Recipient's email ID needs to be mentioned.


String to = "abcd@gmail.com";

// Sender's email ID needs to be mentioned


String from = "mcmohd@gmail.com";

// Assuming you are sending email from localhost


String host = "localhost";

// Get system properties object


Properties properties = System.getProperties();

// Setup mail server


properties.setProperty("mail.smtp.host", host);

// Get the default Session object.


Session mailSession = Session.getDefaultInstance(properties);

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);

// Set From: header field of the header.


message.setFrom(new InternetAddress(from));

// Set To: header field of the header.


message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");

// Now set the actual message


message.setText("This is actual message");

// Send message
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>

<html>
<head>
<title>Send Email using JSP</title>
</head>

<body>
<center>
<h1>Send Email using JSP</h1>
</center>

<p align = "center">


<%
out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>
Let us now put the above code in SendEmail.jsp file and call this JSP
using the URL http://localhost:8080/SendEmail.jsp. This will help send an
email to the given email ID abcd@gmail.com. You will receive the
following response −

Send Email using JSP


Result: Sent message successfully....

If you want to send an email to multiple recipients, then use the


following methods to specify multiple email IDs −

void addRecipients(Message.RecipientType type, Address[] addresses)


throws MessagingException

Here is the description of the parameters −

 type − This would be set to TO, CC or BCC. Here CC represents


Carbon Copy and BCC represents Black Carbon Copy.
Example Message.RecipientType.TO
 addresses − This is the array of email ID. You would need to use
the InternetAddress() method while specifying email IDs

JSP Programming Examples


Example 1
Write a JSP program shows a Sample Order Form.

OrderForm.jsp
<HTML>
<HEAD>
<TITLE>A Catalog Order Form</TITLE>
</HEAD>
<BODY>
<H1 ALIGN="center">A Sample Order Form</H1>
<%!
String item[] = {"DVD", "CD", "Diskette"};
double price[] = {19.99, 12.99, 1.99};
int quantity[] = {2, 9, 24};
%>
<TABLE ALIGN="center" BGCOLOR="lightgray" BORDER="1" WIDTH="75%">
<TR><TD>Item</TD>
<TD>Price</TD>
<TD>Quantity</TD>
<TD>Total Price</TD>
</TR>
<% for (int i=0; i<3; i++) { %>
<TR><TD><%= item[i] %></TD>
<TD><%= price[i] %></TD>
<TD><%= quantity[i] %></TD>
<TD><%= price[i] * quantity[i] %></TD>
</TR>
<% } //end for loop %>
</TABLE>
</BODY>
</HTML>

Example 2
Write a JSP program calculates factorial values for an integer number, while the input is taken
from an HTML form.

input.html
<html>
<body>
<form action="Factorial.jsp">
Enter a value for n: <input type="text" name="val">
<input type="submit" value="Submit">
</form>
</body>
</html>

Factorial.jsp
<html>
<body>
<%!
long n, result;
String str;

long fact(long n) {
if(n==0)
return 1;
else
return n*fact(n-1);
}
%>
<%
str = request.getParameter("val");
n = Long.parseLong(str);
result = fact(n);
%>
<b>Factorial value: </b> <%= result %>
</body>
</html>
Example 3
Write a JSP program shows the Fibonacci series up to a particular term, while the input is taken
from an HTML form.
input.html
<html>
<body>
<form action="Fibonacci.jsp">
Enter a value for n: <input type="text" name="val">
<input type="submit" value="Submit">
</form>
</body>
</html>

Fibonacci.jsp
<html>
<body>
<%!
int n;
String str;

int fibo(int n) {
if(n<2)
return n;
else
return fibo(n-1) + fibo(n-2);
}
%>
<b>Fibonacci series: </b><br>
<%
str = request.getParameter("val");
n = Integer.parseInt(str);

for(int i=0; i<=n; i++) {


out.print(fibo(i) + " ");
}
%>
</body>
</html>

Example 4
Write a JSP program calculates Powers of 2 for integers in the range 0-10.

PowersOf2.jsp
<html>
<head>
<title>Powers of 2</title>
</head>
<body>
<center>
<table border="2" align="center">
<th>Exponent</th>
<th>2^Exponent</th>
<% for (int i=0; i<=10; i++) { //start for loop %>
<tr>
<td><%= i%></td>
<td><%= Math.pow(2, i) %></td>
</tr>
<% } //end for loop %>
</table>
</center>
</body>
</html>

For

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy