CS 702C Web Technology
CS 702C Web Technology
To impart the design, development and implementation of Static and Dynamic Web
Pages.
To develop programs for Web using Scripting Languages and .net framework.
To give an overview of Server Side Programming in Web
CS702C.1 To understand the notions of World Wide Web(www), Internet, HTTP Protocol, Web
Browsers, Client-Server etc.
CS702C.2 To develop interactive web pages using HTML, DHTML and CSS.
CS702C.3 To procure the knowledge of different information interchange formats like XML.
CS702C.4 To design web applications using scripting languages like JavaScript, CGI, PHP.
CS702C.5 To acquire the server side programming concepts using servlet, JSP and .Net framework.
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
C01 1 - 2 - - - - - - - - -
C02 - 2 3 2 - - - - - - - -
C03 - 2 2 - - - - - - - - -
C04 1 2 3 2 - - - - - - - -
C05 1 - 3 2 - - - - - - - -
Module 1: [4L]
Introduction to Web [4L]:Concept of World Wide Web (www), Internet and the relation with
www [1L]; The Internet - Basic Internet Protocols, HTTP Protocol - Request and Response,
Web browser [1L]; Web clients and Web servers, Dynamic IP [1L]; Clients, Servers, and
Communication, Web site design principles, Planning the site and navigation [1L].
CSS, different types- internal, external and inline CSS [1L]; Basic Introduction of DHTML,
Difference between HTML and DHTML, Documentary Object Model (DOM) [1L].
Extended Markup Language (XML) [3L]:Introduction, Difference between HTML & XML,
XML-Tree [1L]; Syntax, Elements, Attributes, Validation and parsing, DTD [2L].
Module 3: [8L]
Java Scripts [3L]:Basic Introduction, Statements, comments, variable, operators, data
types[1L]; condition, switch, loop, break [1L]; Java script functions, objects and events[1L].
CGI Scripts [1L]:Introduction, Environment Variable, GET and POST Methods.
PHP Scripting [4L]:Introduction, Syntax, Variables, Output, Data types, String, Constants[1L];
Operator, Decision Control statements[1L]; switch-case, Loop, PHP function[1L]; array, Form
Handling[1L].
Module-4: [14L]
Java Server Page (JSP) [8L]:
JSP Architecture [1L]; JSP Servers, JSP Life Cycle [1L]; Understanding the layout of JSP, JSP
Scriptlet Tag [1L]; JSP implicit object (request and response) [1L]; Variable declaration,
methods in JSP [1L];JSP directive (Taglib and Include), JavaBean- inserting JavaBean in JSP
[1L];JSP Action tags (Forward & Include) [1L]; Creating ODBC data source name, Introduction
to JDBC, prepared statement and callable statement [1L].
Java Servlet [3L]:Servlet environment and role, Servlet life cycle [1L]; Servlet methods-
Request, Response, Get and post [1L]; Cookies and Session [1L].
.NET Framework [3L]:ASP.Net with MVC introduction, MVC Architecture, MVC routing,
controller, Action method, Action Selector and Action verb, Model and View [1L];.net
framework, C#.net introduction, environment variable, basic syntax of conditional statement,
loop and function[2L].
Text Books:
Recommended books:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
1. "Programming the World Wide Web", Robert. W. Sebesta, Fourth Edition, Pearson
Education, 2007.
2. ”Core Web Programming”- Second Edition-Volume I and II, Marty Hall and Larry Brown,
Pearson Education, 2001.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
1.1.1. Evolution:
World Wide Web was created by Timothy Berners Lee in 1989 at CERN in Geneva.
World Wide Web came into existence as a proposal by him, to allow researchers to work
together effectively and efficiently at CERN. Eventually it became World Wide Web.
The following diagram briefly defines evolution of World Wide Web:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
2.1.1.4. Gopher:
Another tool of the Internet is Gopher, a menu-based program that enables you to browse
for information without knowing where the material is located. It lets you search a list of
resources and then sends the material to you.
2.1.1.5. Telnet:
Telnet lets you log in to a remote computer just as you would if you were there. So any
commands that you would be able to run from the remote computer if you were sitting in front of
it, you would be able to run from the computer you logged in from.
2.2.3. Client:
The HTTP client sends a request to the server in the form of a request method, URI, and
protocol version, followed by a MIME-like message containing request modifiers, client
information, and possible body content over a TCP/IP connection.
2.2.4. Server:
The HTTP server responds with a status line, including the message's protocol version
and a success or error code, followed by a MIME-like message containing server information,
entity meta information, and possible entity-body content.
2.2.5. Request and Response:
The operation of Hypertext Transfer Protocol (HTTP) involves the communication
between a Hypertext Transfer Protocol (HTTP) client application (Usually web browser) and a
Hypertext Transfer Protocol (HTTP) server application (Web servers like IIS). Hypertext
Transfer Protocol (HTTP) uses Transmission Control Protocol (TCP) as the Transport Layer
Protocol at Well Known port number 80. Once the TCP connection is established, the two steps
in Hypertext Transfer Protocol (HTTP) communication are:
1. HTTP Client Request: Hypertext Transfer Protocol (HTTP) client sends an
Hypertext Transfer Protocol (HTTP) Request to the Hypertext Transfer Protocol
(HTTP) Server according to the HTTP standard, specifying the information the client
like to retrieve from the Hypertext Transfer Protocol (HTTP) Server.
2. HTTP Server Response: Once the Hypertext Transfer Protocol (HTTP) Request
arrived at the Hypertext Transfer Protocol (HTTP) server, it will process the request
and creates a Hypertext Transfer Protocol (HTTP) Response message. The Hypertext
Transfer Protocol (HTTP) response message may contain the resource the Hypertext
Transfer Protocol (HTTP) Client requested or information why the Hypertext
Transfer Protocol (HTTP) request failed.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
3.1.2.3. Examples:
Following table describes the most leading web servers available today:
FreeBSD operating system. This open source web server is fast, secure and
consumes much less CPU power. Lighttpd can also run on Windows, Mac OS X,
Linux and Solaris operating systems.
Sun Java System Web Server
This web server from Sun Microsystems is suited for medium and large web sites.
4. Though the server is free it is not open source. It however, runs on Windows, Linux
and UNIX platforms. The Sun Java System web server supports various languages,
scripts and technologies required for Web 2.0 such as JSP, Java Servlets, PHP, Perl,
Python, and Ruby on Rails, ASP and Coldfusion etc.
Jigsaw Server
Jigsaw (W3C's Server) comes from the World Wide Web Consortium. It is open
5.
source and free and can run on various platforms like Linux, UNIX, Windows, and
Mac OS X Free BSD etc. Jigsaw has been written in Java and can run CGI scripts
and PHP programs.
The Web is a familiar client-server application. To see a Web page, you run a Web client
like Internet Explorer or Firefox. When you enter a URL and hit enter, the client encloses it in a
Get message which it sends across the network to a Web server. If the document is on that Web
server, it sends it back to the client. If not, it sends an error message (formatted as a Web page).
When the client receives the page (pr error message), it formats and displays it.
3. if the server has the requested document, it sends it back to the client
4. if the server does not have the document, it sends an error message back to the client
5. the client displays whatever was returned
6. the server waits for the next request
This dialog between the client and the server follows a specific pattern or protocol. The
protocol specifies the format of messages that can be sent and their meanings. The Web protocol
is called the Hypertext Transfer Protocol (HTTP).
Note that when information is transferred from a server to a client as in this case, we
speak of downloading and when we transfer information to a server we speak of uploading.
Surfing the Web with a Web client is a popular application, but there are many other
application protocols, for example:
Protocol Application
FTP, File Transfer copy files from client to server or from server to client
Note that the terms "client" and "server" refer both to the computer hardware and the
program it is running. When you are looking at things on the Internet, your computer is the client
hardware and it is running a client program.
In the case of the Web, people also refer to a client program as a browser since it is used
to browse through the contents of Web sites.
simple looking website with exceptional usability and well-structured, typically performs
amazingly on Google. User views of such websites are also higher than those with poor user
experience. The performance entirely depends on the effectiveness of the website.
So, how to design a good website?
Good website design needs a wide range of professionals having expertise in different
areas. Their collective efforts need to put in when there is a critical decision to take place. Here
in this article, we’ll outline the 8 essential principles of good website design which must be
pondered while developing a website. These design principles will definitely help web designers
to develop awe-inspiring designs and to enhance the usability of a website.
Here is the list of 8-good design principles which will make your website aesthetic, user-
friendly, effective, and engaging:
4.2.1. Simple is the best:
Over-designed website may not work. Putting too many elements on the page may lead to
distract visitors from the main purpose of your website. Simplicity always works in an effective
web page design. Clean and fresh design of your website not only makes the website appealing,
but also help user to navigate from one page to another seamlessly. Loading a website having
design features which do not serve the purpose may be frustrating. Keep your design as simple as
possible so that the visitors can feel it easy-to-use and can find their ways easily.
4.2.2. Consistency:
Consistency in website design matter a lot. Give your attention to match design elements
throughout each of the pages. It can be understood that your fonts, sizes, headings, sub-headings,
and button styles must be the same throughout the website. Plan everything in advance. Finalize
the fonts and the right colors for your texts, buttons etc., and stick to them throughout the
development. CSS (Cascading Style Sheets) would come in handy to keep the complete
information about design styles and elements.
4.2.3. Typography & Readability:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
No matter how good your design is text still rules the website as it provides users the
desired information. Since search engine crawlers are very much familiar with this data, it
becomes an integral part of SEO activities. You should keep your typography visually appealing
and readable for visitors, along with tricky use of keywords, meta-data, and other SEO-sensitive
elements.
Consider using fonts that are easier to read. The modern sans-serif fonts as Arial,
Helvetica etc. can be used for the body texts. Make proper combinations of typefaces for each
and every design elements such as headlines, body texts, buttons etc.
4.2.4. Mobile compatibility:
Keeping in mind the ever-growing usage of smartphones, tablets and phablets, web
design must be effective for various screens. If your website design doesn’t support all screen
sizes, chance is that you’ll lose the battle to your competitors. There are a number of web design
studios or service points from where you can turn your desktop design into a responsive and
adaptive one for all screen sizes.
4.2.5. Color palette and imagery:
A perfect color combination attracts users while a poor combination can lead to
distraction. This necessitates you to pick a perfect color palette for your website which can create
a pleasing atmosphere, thus leaving a good impact on visitors. Enhance users experience by
selecting complementary color palette to give a balanced-look to your website design.
Remember to white space use as it avoids your website from visual clutter and mess. Also avoid
using too many colors. 3 or 4 tones for the whole websites are ample to give appealing and clear
design.
Same is the case with images. Don’t use multiple vibrant images.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
No one likes the website that takes too much time to load. So take care of it by
optimizing image sizes, combing code into a central CSS or JavaScript file as it reduces HTTP
requests. Also, compress HTML, JavaScript and CSS for enhanced loading speed.
4.2.7. Easy Navigation:
Study shows that visitors stay more time on the websites having easy navigation. For
effective navigation, you may consider creating a logical page hierarchy, using bread scrums,
and designing clickable buttons. You should follow the “three-click-rule” so that visitors can get
the required information within three clicks.
4.2.8. Communication:
The ultimate purpose of the visitors is to get information, and if your website is able to
communicate your visitors efficiently, most probably they would spend more time on your
website. Tricks that may work to establish effortless communication with the visitors are –
organizing information by making good use of headlines and sub-headlines, cutting the waffle,
and using bullet points, rather than long gusty sentences.
To wrap it up
Keeping the aforementioned principles of good website design, you can easily develop an
aesthetic and functional website. Without this base, it would be difficult to travel a long path.
Only with a clean and user-friendly design, you can think to succeed.
4.3. Planning the site and navigation:
Web navigation refers to the process of navigating a network of information resources in
the World Wide Web, which is organized as hypertext or hypermedia. The user interface that is
used to do so is called a web browser.
A central theme in web design is the development of a web navigation interface that
maximizes usability.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
3. Local website navigation:Local navigation is the links within the text of a given web
page, linking to other pages within the website.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Sitemap: A site map (or sitemap) is a list of pages of a web site accessible to
crawlers or users. It can be either a document in any form used as a planning tool for
Web design, or a Web page that lists the pages on a Web site, typically organized in
hierarchical fashion.
Named anchor: An anchor element is called an anchor because web designers can
use it to anchor a URL to some text on a web page. When users view the web page in
a browser, they can click the text to activate the link and visit the page whose URL is
in the link.
HTML tags are keywords (tag names) surrounded by angle brackets like <html>
HTML tags normally come in pairs like <p> and </p>
The first tag in a pair is the start tag, the second tag is the end tag
The end tag is written like the start tag, with a slash before the tag name
Start and end tags are also called opening tags and closing
tags<tagname>content</tagname>
<html>
<body>
<h1>This a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
1.1.6. The <!DOCTYPE> Declaration:
The <!DOCTYPE> declaration helps the browser to display a web page correctly. There
are many different documents on the web, and a browser can only display an HTML page 100%
correctly if it knows the HTML version and type used.
Common Declarations
HTML5
<!DOCTYPE html>
1.1.7. Write HTML Using Notepad or TextEdit:
HTML can be edited by using a professional HTML editor like:
Adobe Dreamweaver
Microsoft Expression Web
Coffee Cup HTML Editor
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
However, for learning HTML we recommend a text editor like Notepad (PC) or TextEdit
(Mac).
We believe using a simple text editor is a good way to learn HTML.
Follow the 4 steps below to create your first web page with Notepad.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
The start tag is often called the opening tag. The end tag is often called the closing tag.
1.2.1. HTML Element Syntax:
An HTML element starts with a start tag / opening tag
An HTML element ends with an end tag / closing tag
The element content is everything between the start and the end tag
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Most HTML elements can be nested (can contain other HTML elements).HTML
documents consist of nested HTML elements.
1.2.3. HTML Document Example:
<!DOCTYPE html>
<html>
<body>
<p>This is my first paragraph.</p>
</body>
</html>
The example above contains 3 HTML elements.
1.2.4. HTML Example Explained:
<body>
<p>This is my first paragraph.</p>
</body>
<html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<body>
<p>This is my first paragraph.</p>
</body>
</html>
<p>This is a paragraph
<p>This is a paragraph
The example above works in most browsers, because the closing tag is considered
optional.
Never rely on this. Many HTML elements will produce unexpected results and/or errors
if you forget the end tag.
1.2.5. Empty HTML Elements:
HTML elements with no content are called empty elements.
<br> is an empty element without a closing tag (the <br> tag defines a line break).
Tip: In XHTML, all elements must be closed. Adding a slash inside the start tag, like <br/>, is
the proper way of closing empty elements in XHTML (and XML).
Example
Tag Description
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<h1> defines the most important heading. <h6> defines the least important heading.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Note: Browsers automatically add some empty space (a margin) before and after each
heading.
The <p> tag defines a paragraph. Browsers automatically add some space (margin) before
and after each <p> element. The margins can be modified with CSS (with the margin
properties).
Another example
These HTML tags are called formatting tags (look at the bottom of this page for a
complete reference).
<strong> or <em> means that you want the text to be rendered in a way that the user understands
as "important". Today, all major browsers render strong as bold and em as italics. However, if a
browser one day wants to make a text highlighted with the strong feature, it might be cursive for
example and not bold!
1.6.3. HTML Text Formatting Tags:
Tag Description
<b> Defines bold text
<em> Defines emphasized text
<i> Defines a part of text in an alternate voice or mood
<small> Defines smaller text
<strong> Defines important text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<mark> Defines marked/highlighted text
Example
<a href="http://www.yahoo.com/">Visit yahoo</a>
1.6.4.1.1. HTML Links - The target attribute:
The target attribute specifies where to open the linked document.
The example below will open the linked document in a new browser window or a new
tab:
Tip: Bookmarks are not displayed in any special way. They are invisible to the reader.
Example
Create a link to the "Useful Tips Section" inside the same document:
Or, create a link to the "Useful Tips Section" from another page:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<a href="http://www.w3schools.com/html_links.htm#tips">
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
1.6.7. The HTML <base> Element:
The <base> tag specifies the base URL/target for all relative URLs in a page:
<head>
<base href="http://www.gnit.com/images/" target="_blank">
</head>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The <link> tag defines the relationship between a document and an external resource.
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
1.6.9. The HTML <style> Element:
The <style> tag is used to define style information for an HTML document.
Inside the <style> element you specify how HTML elements should render in a browser:
<head>
<style type="text/css">
body {background-color:yellow;}
p {color:blue;}
</style>
</head>
1.6.10. The HTML <meta> Element:
The <meta> tag provides metadata about the HTML document. Metadata will not be
displayed on the page, but will be machine parsable.
Meta elements are typically used to specify page description, keywords, author of the
document, last modified, and other metadata.
The metadata can be used by browsers (how to display content or reload page), search
engines (keywords), or other web services.
Tag Description
<base> Defines a default address or a default target for all links on a page
1.6.12.1. <meta>:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
1.6.12.3. <style>:
Lecture 2: Link, Table, List, Block, Layout, Html Forms and input
2.1. HTML Links:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
<a href="http://www.yahoo.com/">Visit yahoo</a>
2.1.1.1. HTML Links - The target attribute:
The target attribute specifies where to open the linked document.
The example below will open the linked document in a new browser window or a new
tab:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Tip: Bookmarks are not displayed in any special way. They are invisible to the reader.
Example
Create a link to the "Useful Tips Section" inside the same document:
Or, create a link to the "Useful Tips Section" from another page:
<a href="http://www.w3schools.com/html_links.htm#tips">
A table is divided into rows with the <tr> tag. (tr stands for table row)
A row is divided into data cells with the <td> tag. (td stands for table data)
A row can also be divided into headings with the <th> tag. (th stands for table heading)
The <td> elements can contain all sorts of HTML elements like text, images, lists, other
tables, etc.
If you do not specify a border for the table, it will be displayed without borders.
Cell padding specifies the space between the cell content and its borders.
If you do not specify a padding, the table cells will be displayed without padding.
<html>
<head>
<style>
table, th, td
{
border-collapse:collapse;
border:1px solid black;
}
th, td
{
padding:15px;
}
</style>
</head>
<body>
<table style="width:300px">
<tr>
<td>Jill</td>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<p>Try to change the padding to 5px.</p>
</body>
</html>
To set the cell spacing for the table, use the CSS border-spacing property.
<html>
<head>
<style>
table, th, td
{
border:1px solid black;
padding:5px;
}
table
{
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
border-spacing:15px;
}
</style>
</head>
<body>
<table style="width:300px">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>
List item
List item
List item
Most HTML elements are defined as block level elements or as inline elements.
Block level elements normally start (and end) with a new line when displayed in a
browser.
Examples: <h1>, <p>, <ul>, <table>
The HTML <div> element is a block level element that can be used as a container for
grouping other HTML elements. The<div> element has no special meaning. Except that, because
it is a block level element, the browser will display a line break before and after it.When used
together with CSS, the <div> element can be used to set style attributes to large blocks of
content. Another common use of the <div> element, is for document layout. It replaces the "old
way" of defining layout using tables. Using <table> elements for layout is not the correct use of
<table>. The purpose of the <table> element is to display tabular data.
The HTML <span> element is an inline element that can be used as a container for text.
The <span> element has no special meaning.
When used together with CSS, the <span> element can be used to set style attributes to
parts of the text.
The most important form element is the <input> element.The <input> element is used to
select user information. An <input> element can vary in many ways, depending on the type
attribute. An <input> element can be of type text field, checkbox, password, radio button, submit
button, and more.The most common input types are described below.
2.6.2.1. Text Fields:
<input type="text"> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<form>
Password: <input type="password" name="pwd">
</form>
Password:
Note: The characters in a password field are masked (shown as asterisks or circles).
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
A submit button is used to send form data to a server. The data is sent to the page
specified in the form's action attribute. The file defined in the action attribute usually does
something with the received input.
Username:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
If you type some characters in the text field above, and click the "Submit" button, the
browser will send your input to a page called "demo_form_action.asp". The page will show you
the received input.
<iframe src="URL"></iframe>
The height and width attributes are used to specify the height and width of the iframe.
The attribute values are specified in pixels by default, but they can also be in percent (like
"80%").
Example
CSS colors are defined using a hexadecimal (hex) notation for the
combination of Red, Green, and Blue color values (RGB). The lowest value that
can be given to one of the light sources is 0 (hex 00). The highest value is 255
(hex FF).Hex values are written as 3 double digit numbers, starting with a #
sign.
#FF0000 rgb(255,0,0)
#00FF00 rgb(0,255,0)
#0000FF rgb(0,0,255)
#FFFF00 rgb(255,255,0)
#00FFFF rgb(0,255,255)
#FF00FF rgb(255,0,255)
#C0C0C0 rgb(192,192,192)
#FFFFFF rgb(255,255,255)
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Color Names Supported by All Browsers.140 color names are defined in the HTML and
CSS color specification (17 standard colors plus 123 more). The table below lists them all, along
with their hexadecimal values. Tip: The 17 standard colors are: aqua, black, blue, fuchsia, gray,
green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow.
4. Image Map:
4.1. HTML <map> Tag:
The <map> tag is used to define a client-side image-map. An image-map is an image
with clickable areas.The required name attribute of the <map> element is associated with the
<img>'s usemap attribute and creates a relationship between the image and the map. The <map>
element contains a number of <area> elements that defines the clickable areas in the image map.
<!DOCTYPE html>
<html>
<body>
<p>Click on the sun or on one of the planets to watch it closer:</p>
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
1. <map>:- name(attribute)
2. <img>:- usemap , src, alt(attribute)
3. <area>:- shape, cords, alt, href (attribute)
The required name attribute specifies the name of an image-map.The name attribute is
associated with the <img>'s usemap attribute and creates a relationship between the image and
the map.
4.4. HTML Images - The <img> Tag and the src Attribute:
In HTML, images are defined with the <img> tag.The <img> tag is empty, which means
that it contains attributes only, and has no closing tag.To display an image on a page, you need to
use the src attribute. src stands for "source". The value of the src attribute is the URL of the
image you want to display.
The URL points to the location where the image is stored. An image named "boat.gif",
located in the "images" directory on "www.abc.com" has the URL:
http://www.abc.com/images/boat.gif.
The browser displays the image where the <img> tag occurs in the document. If you put
an image tag between two paragraphs, the browser shows the first paragraph, then the image, and
then the second paragraph.
The required alt attribute specifies an alternate text for an image, if the image cannot be
displayed.
The value of the alt attribute is an author-defined text:
The alt attribute provides alternative information for an image if a user for some reason
cannot view it (because of slow connection, an error in the src attribute, or if the user uses a
screen reader).
The <area> tag defines an area inside an image-map (an image-map is an image with
clickable areas).The <area> element is always nested inside a <map> tag.
Note: The usemap attribute in the <img> tag is associated with the <map> element's
name attribute, and creates a relationship between the image and the map.
Value Description
Specifies the coordinates of the left, top, right, bottom corner of the
x1,y1,x2,y2
rectangle (for shape="rect")
Specifies the coordinates of the circle center and the radius (for
x,y,radius
shape="circle")
Specifies the coordinates of the edges of the polygon. If the first and last
x1,y1,x2,y2,..,xn,yn coordinate pairs are not the same, the browser will add the last coordinate
pair to close the polygon (for shape="poly")
Value Description
#mapname A hash character ("#") plus the name or id of the <map> element to use
Value Description
The shape attribute specifies the shape of an area.The shape attribute is used
together with the coords attribute to specify the size, shape, and placement of an area.
Value Description
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended
to simplify the process of making web pages presentable.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
CSS handles the look and feel part of a web page. Using CSS, you can control the color
of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid
out, what background images or colors are used, layout designs, and variations in display for
different devices and screen sizes as well as a variety of other effects.
CSS is easy to learn and understand but it provides powerful control over the presentation
of an HTML document. Most commonly, CSS is combined with the markup languages HTML or
XHTML.
5.2. Advantages of CSS:
CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages
as you want.
Pages load faster − If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag.
So less code means faster download times.
Easy maintenance − To make a global change, simply change the style, and all elements
in all the web pages will be updated automatically.
Superior styles to HTML − CSS has a much wider array of attributes than HTML, so
you can give a far better look to your HTML page in comparison to HTML attributes.
Multiple Device Compatibility − Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So it’s a good idea to start using CSS in all the HTML pages
to make them compatible to future browsers.
5.3. Internal Style Sheet:
An internal style sheet can be used if one single document has a unique style. Internal
styles are defined in the <head> section of an HTML page, by using the <style> tag, like this:
<head>
<style>
body {background-color:yellow;}
p {color:blue;}
</style>
</head>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
An external style sheet is ideal when the style is applied to many pages. With an
external style sheet, you can change the look of an entire Web site by changing one file. Each
page must link to the style sheet using the <link> tag. The <link> tag goes inside the <head>
section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>My First CSS Example</h1>
<p>This is a paragraph.</p>
</body>
</html>
HTML
HTML stands for Hypertext Markup Language and it is a client-side markup language. It
is used to build the block of web pages.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
JavaScript
It is a Client-side Scripting language. JavaScript is supported by most of the browser, also
have cookies collection to determine the user needs.
CSS
The abbreviation of CSS is Cascading Style Sheet. It helps in the styling of the web pages
and helps in designing of the pages. The CSS rules for DHTML will be modified at different
levels using JS with event handlers which adds a significant amount of dynamism with very little
code.
DOM
It is known as a dynamic Object Model which act as the weakest links in it. The only
defect in it is that most of the browser does not support DOM. It is a way to manipulate the static
contents.
Note: Many times DHTML is confused with being a language like HTML but it is not. It
must be kept in mind that it is an interface or browsers enhancement feature which makes it
possible to access the object model through JavaScript language and hence make the webpage
more interactive.
DHTML makes a webpage dynamic but JavaScript also does, the question arises that
what different does DHTML do? So the answer is that DHTML has the ability to change a
webpages look, content and style once the document has loaded on our demand without
changing or deleting everything already existing on the browser’s webpage. DHTML can change
the content of a webpage on demand without the browser having to erase everything else, i.e.
being able to alter changes on a webpage even after the document has completely loaded.
6.4. Advantages:
Size of the files are compact in compared to other interactional media like Flash or
Shockwave, and it downloads faster.
It is supported by big browser manufacturers like Microsoft and Netscape.
Highly flexible and easy to make changes.
Viewer requires no extra plug-ins for browsing through the webpage that uses
DHTML; they do not need any extra requirements or special software to view it.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
User time is saved by sending less number of requests to the server. As it is possible
to modify and replace elements even after a page is loaded, it is not required to create
separate pages for changing styles which in turn saves time in building pages and also
reduces the number of requests that are sent to the server.
It has more advanced functionality than a static HTML. It is capable of holding more
content on the web page at the same time.
6.5. Disadvantages:
It is not supported by all the browsers. It is supported only by recent browsers such as
Netscape 6, IE 5.5, and Opera 5 like browsers.
Learning of DHTML requires a lot of pre-requisites languages such as HTML, CSS,
JS, etc should be known to the designer before starting with DHTML which is a long
and time-consuming in itself.
Implementation of different browsers are different. So if it worked in one browser, it
might not necessarily work the same way in another browser.
Even after being great with functionality, DHTML requires a few tools and utilities
that are some expensive. For example, the DHTML text editor, Dreamweaver. Along
with it the improvement cost of transferring from HTML to DHTML makes cost rise
much higher.
The HTML DOM is a standard object model and programming interface for HTML. It
defines:
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
When a web page is loaded, the browser creates a Document Object Model of the page.
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
XML was designed to transport and store data, with focus on what data is.
HTML was designed to display data, with focus on how data looks.
The note above is quite self-descriptive. It has sender and receiver information, it also has
a heading and a message body.
But still, this XML document does not DO anything. It is just information wrapped in
tags. Someone must write a piece of software to send, receive or display it.
7.4. With XML You Invent Your Own Tags:
The tags in the example above (like <to> and <from>) are not defined in any XML
standard. These tags are "invented" by the author of the XML document.
That is because the XML language has no predefined tags.
The tags used in HTML are predefined. HTML documents can only use tags defined in
the HTML standard (like <p>, <h1>, etc.).
XML allows the author to define his/her own tags and his/her own document structure.
7.5. XML is Not a Replacement for HTML:
XML is a complement to HTML.
It is important to understand that XML is not a replacement for HTML. In most web
applications, XML is used to transport data, while HTML is used to format and display the data.
My best description of XML is this:
XML is a software- and hardware-independent tool for carrying information.
7.6. USE OF XML:
XML Separates Data from HTML
If you need to display dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes.With XML, data can be stored in separate XML files.
This way you can concentrate on using HTML/CSS for display and layout, and be sure that
changes in the underlying data will not require any changes to the HTML.With a few lines of
JavaScript code, you can read an external XML file and update the data content of your web
page.
XML Simplifies Data Sharing
In the real world, computer systems and databases contain data in incompatible
formats.XML data is stored in plain text format. This provides a software and
hardwareindependent way of storing data.This makes it much easier to create data that can be
shared by different applications.
XML Simplifies Data Transport
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.Exchanging data as XML greatly reduces this
complexity, since the data can be read by different incompatible applications.
XML Simplifies Platform Changes
Upgrading to new systems (hardware or software platforms), is always time consuming.
Large amounts of data must be converted and incompatible data is often lost.XML data is stored
in text format. This makes it easier to expand or upgrade to new operating systems, new
applications, or new browsers, without losing data.
XML Makes Your Data More Available
Different applications can access your data, not only in HTML pages, but also from XML
data sources.With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc.), and make it more available for blind people, or
people with other disabilities.
7.7. XML is used to Create New Internet Languages:
A lot of new Internet languages are created with XML.
Here are some examples:
XHTML
WSDL for describing available web services
WAP and WML as markup languages for handheld devices
RSS languages for news feeds
RDF and OWL for describing resources and ontology
SMIL for describing multimedia for the web
The first line is the XML declaration. It defines the XML version (1.0).The next line
describes the root element of the document (like saying: "this document is a note"):
<note>
The next 4 lines describe 4 child elements of the root (to, from, heading, and body):
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
And finally the last line defines the end of the root element :</note>
You can assume, from this example, that the XML document contains a note to Tove
from Jani.Don't you agree that XML is pretty self-descriptive?
7.8.1. XML Documents Form a Tree Structure:
XML documents must contain a root element. This element is "the parent" of all other
elements.The elements in an XML document form a document tree. The tree starts at the root
and branches to the lowest level of the tree.
All elements can have sub elements (child elements):
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
The terms parent, child, and sibling are used to describe the relationships between
elements. Parent elements have children. Children on the same level are called siblings (brothers
or sisters).All elements can have text content and attributes (just like in HTML).
Example
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The root element in the example is <bookstore>. All <book> elements in the document
are contained within <bookstore>.The <book> element has 4 children: <title>, < author>,
<year>, <price>.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<p>This is a paragraph.
<br>
In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
<p>This is a paragraph.</p>
<br />
Note: You might have noticed from the previous example that the XML declaration did
not have a closing tag. This is not an error. The declaration is not a part of the XML document
itself, and it has no closing tag.
8.1.2. XML Tags are Case Sensitive:
XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<Message>This is incorrect</message>
<message>This is correct</message>
Note: "Opening and closing tags" are often referred to as "Start and end tags". Use
whatever you prefer. It is exactly the same thing.
8.1.3. XML Elements Must be Properly Nested:
In HTML, you might see improperly nested elements:
<b><i>This text is bold and italic</b></i>
In XML, all elements must be properly nested within each other:
<b><i>This text is bold and italic</i></b>
In the example above, "Properly nested" simply means that since the <i> element is
opened inside the <b> element, it must be closed inside the <b> element.
8.1.4. XML Documents Must Have a Root Element:
XML documents must contain one element that is the parent of all other elements. This
element is called the rootelement.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
8.1.5. XML Attribute Values Must be quoted:
XML elements can have attributes in name/value pairs just like in HTML.In XML, the
attribute values must always be quoted.Study the two XML documents below. The first one is
incorrect, the second is correct:
<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The error in the first document is that the date attribute in the note element is not quoted.
8.1.6. Entity References:
Some characters have a special meaning in XML.If you place a character like "<" inside
an XML element, it will generate an error because the parser interprets it as the start of a new
element.This will generate an XML error:
To avoid this error, replace the "<" character with an entity reference:
Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than
character is legal, but it is a good habit to replace it.
Camel case <firstName> Uppercase first letter in each word except the first
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
MESSAGE
To: Tove
From: Jani
Imagine that the author of the XML document added some extra information to it:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Should the application break or crash?
No. The application should still be able to find the <to>, <from>, and <body> elements in
the XML document and produce the same output.One of the beauties of XML, is that it can be
extended without breaking applications.
8.3. XML Attributes:
XML elements can have attributes, just like HTML.Attributes provide additional
information about an element.
In HTML, attributes provide additional information about elements:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<img src="computer.gif">
<a href="demo.asp">
Attributes often provide information that is not a part of the data. In the example below,
the file type is irrelevant to the data, but can be important to the software that wants to
manipulate the element:
<file type="gif">computer.gif</file>
8.3.1. XML Attributes Must be quoted:
Attribute values must always be quoted. Either single or double quotes can be used. For a
person's sex, the person element can be written like this:
<person sex="female">
or like this:
<person sex=’female’>
If the attribute value itself contains double quotes you can use single quotes, like in this
example:
<gangster name='George "Shotgun" Ziegler'>
or you can use character entities:
<gangster name="George "Shotgun" Ziegler">
8.3.2. XML Elements vs. Attributes:
Take a look at these examples:
<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
In the first example sex is an attribute. In the last, sex is an element. Both examples
provide the same information.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
There are no rules about when to use attributes or when to use elements. Attributes are
handy in HTML. In XML my advice is to avoid them. Use elements instead.
8.3.3. My Favorite Way:
The following three XML documents contain exactly the same information:
A date attribute is used in the first example:
<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
A date element is used in the second example:
<note>
<date>10/01/2008</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
An expanded date element is used in the third: (THIS IS MY FAVORITE):
<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
8.3.4. Avoid XML Attributes?
Some of the problems with using attributes are:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Attributes are difficult to read and maintain. Use elements for data. Use attributes for
information that is not relevant to the data.
Don't end up like this:
<note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
The above example is said to be well-formed as −
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
It defines the type of document. Here, the document type is element type.
It includes a root element named as address.
Each of the child elements among name, company and phone is enclosed in its self-
explanatory tag.
Order of the tags is maintained.
Xerces − Xerces is implemented in Java and is developed by the famous open source
Apache Software Foundation.
9.3. XML - DTDs:
The XML Document Type Declaration, commonly known as DTD, is a way to describe
XML language precisely. DTDs check vocabulary and validity of the structure of XML
documents against grammatical rules of appropriate XML language.
An XML DTD can be either specified inside the document, or it can be kept in a separate
document and then liked separately.
Syntax
Basic syntax of a DTD is as follows –
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>
In the above syntax,
Where root-element is the name of root element and element-declarations is where you
declare the elements.
Example
Following is a simple example of internal DTD –
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Let us go through the above code –
Start Declaration − Begin the XML declaration with the following statement.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
DTD − Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE −
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name.
The DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations.
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Several elements are declared here that make up the vocabulary of the <name> document.
<!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA". Here
#PCDATA means parse-able text data.
End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket
and a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML
document follows immediately.
9.3.1.1. Rules:
The document type declaration must appear at the start of the document (preceded
only by the XML header) − it is not permitted anywhere else within the document.
Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.
The Name in the document type declaration must match the element type of the root
element.
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd is as shown –
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
9.3.2.1. Types:
You can refer to an external DTD by using either system identifiers or public identifiers.
9.3.2.1.1. System Identifiers:
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows −
<!DOCTYPE name SYSTEM "address.dtd" [...]>
As you can see, it contains keyword SYSTEM and a URI reference pointing to the
location of the document.
9.3.2.1.2. Public Identifiers:
Public identifiers provide a mechanism to locate DTD resources and is written as follows
–
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier.
Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any
format, however, a commonly used format is called Formal Public Identifiers, or FPIs.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off
the light</button>
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
This statement tells the browser to write "Hello GNIT." inside an HTML element with
id="demo":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>In HTML, JavaScript statements are executed by the browser.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello GNIT.";
</script>
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Output
JavaScript Statements
In HTML, JavaScript statements are executed by the browser.
Hello GNIT
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>
<p id="demo1"></p>
<script>
var a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
Output
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
</body>
</html>
1.4.2. Multi-line Comments:
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>
1.5.1. Identifiers:
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
1.5.2. Variables:
You can declare many variables in one statement.Start the statement with var and
separate the variables by comma:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>You can declare many variables in one statement.</p>
<p id="demo"></p>
<script>
var person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>
</body>
</html>
Operato Description
r
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Remainder)
++ Increment
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
-- Decrement
Operato Description
r
== equal to
=== equal value and equal type
!= not equal
!= = not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Operator Description
&& logical and
|| logical or
! logical not
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed
numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010
1.7. JavaScript Data Types:
JavaScript variables can hold many data types: numbers, strings, objects and more:
var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object
In programming, data type is an important concept.To be able to operate on variables, it
is important to know something about the type.
Without data types, a computer cannot safely solve this:
var x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it
produce a result?
JavaScript will treat the example above as:
var x = "16" + "Volvo";
Lecture 2: JavaScript condition, switch, loop, and break
2.1. JavaScript – if,if-else,if-else-if Statement:
While writing a program, there may be a situation when you need to adopt one out of a
given set of paths. In such cases, you need to use conditional statements that allow your program
to make correct decisions and perform right actions.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
JavaScript supports conditional statements which are used to perform different actions
based on different conditions. Here we will explain the if..else statement.
Flow Chart of if-else
The following flow chart shows how the if-else statement works.
Decision Making
if statement
if...else statement
if...else if... statement
2.1.1. if statement:
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s)
in the else block are executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
You can use multiple if...else…if statements, as in the previous chapter, to perform a
multiway branch. However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else if statements.
Flow Chart
The following flow chart explains a switch-case statement works.
...
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
Example
Try the following example to implement switch-case statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following code that
uses switch-case statement without any break statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...
2.3. JavaScript Loop:
The 'for' loop is the most compact form of looping. It includes the following three
important parts –
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition
is true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The break statement, which was briefly introduced with the switch statement, is used to
exit a loop early, breaking out of the enclosing curly braces.
Flow Chart
Example
The following example illustrates the use of a break statement with a while loop. Notice
how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just
below to the closing curly brace –
<html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
We already have seen the usage of break statement inside a switch statement.
The continue statement tells the interpreter to immediately start the next iteration of the
loop and skip the remaining code block. When a continue statement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5 –
<html>
<body>
<scripttype="text/javascript">
<!--
var x =1;
document.write("Entering the loop<br /> ");
while(x <10){
x = x +1;
if(x ==5){
continue;// skip rest of the loop body
}
document.write( x +"<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again. It helps programmers in
writing modular codes. Functions allow a programmer to divide a big program into a number of
small and manageable functions.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions like alert() and
write() in the earlier chapters. We were using these functions again and again, but they had been
written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to
write your own functions in JavaScript.
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique function name, a
list of parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
Example
Try the following example. It defines a function called sayHello that takes no parameters
−
<scripttype="text/javascript">
<!--
function sayHello(){
alert("Hello there");
}
//-->
</script>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
To invoke a function somewhere later in the script, you would simply need to write the
name of that function as shown in the following code.
<html>
<head>
<scripttype="text/javascript">
function sayHello(){
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<inputtype="button"onclick="sayHello()"value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take multiple
parameters separated by comma.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
Try the following example. We have modified our sayHello function here. Now it takes
two parameters.
<html>
<head>
<scripttype="text/javascript">
function sayHello(name, age){
document.write (name +" is "+ age +" years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<inputtype="button"onclick="sayHello('Zara',7)"value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
A JavaScript function can have an optional return statement. This is required if you want
to return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the
function to return their multiplication in your calling program.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.
<html>
<head>
<scripttype="text/javascript">
function concatenate(first, last){
var full;
full = first + last;
return full;
}
function secondFunction(){
var result;
result = concatenate('Zara','Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<inputtype="button"onclick="secondFunction()"value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Inheritance − the capability of a class to rely upon another class (or number of
classes) for some of its properties and methods.
Object properties can be any of the three primitive data types, or any of the abstract data
types, such as another object. Object properties are usually variables that are used internally in
the object's methods, but can also be globally visible variables that are used throughout the page.
objectName.objectProperty = propertyValue;
Example
The following code gets the document title using the "title" property of the document
object.
Methods are the functions that let the object do something or let something be done to it.
There is a small difference between a function and a method – at a function is a standalone unit
of statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen
to performing complex mathematical operations on a group of local properties and parameters.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
Following is a simple example to show how to use the write() method of document
object to write any content on the document.
document.write("This is test");
All user-defined objects and built-in objects are descendants of an object called Object.
The new operator is used to create an instance of an object. To create an object, the new
operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date().
These constructors are built-in JavaScript functions.
JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and virtually
any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
3.3.1. onclick Event Type:
This is the most frequently used event type which occurs when a user clicks the left
button of his mouse. You can put your validation, warning etc., against this event type.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
<html>
<head>
<scripttype="text/javascript">
<!--
function sayHello(){
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<inputtype="button"onclick="sayHello()"value="Say Hello"/>
</form>
</body>
</html>
The standard HTML 5 events are listed here for your reference. Here script indicates a
JavaScript function to be executed against that event.
buffering
Triggers when media can be played to the end, without stopping
oncanplaythrough script
for buffering
onchange script Triggers when an element changes
onclick script Triggers on a mouse click
oncontextmenu script Triggers when a context menu is triggered
ondblclick script Triggers on a mouse double-click
ondrag script Triggers when an element is dragged
ondragend script Triggers at the end of a drag operation
Triggers when an element has been dragged to a valid drop
ondragenter script
target
Triggers when an element is being dragged over a valid drop
ondragleave script
target
ondragover script Triggers at the start of a drag operation
ondragstart script Triggers at the start of a drag operation
ondrop script Triggers when dragged element is being dropped
ondurationchange script Triggers when the length of the media is changed
Triggers when a media resource element suddenly becomes
onemptied script
empty.
onended script Triggers when media has reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the window gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets user input
onhaschange script Triggers when the document has change
oninput script Triggers when an element gets user input
oninvalid script Triggers when an element is invalid
onkeydown script Triggers when a key is pressed
onkeypress script Triggers when a key is pressed and released
onkeyup script Triggers when a key is released
onload script Triggers when the document loads
onloadeddata script Triggers when media data is loaded
Triggers when the duration and other media data of a media
onloadedmetadata script
element is loaded
onloadstart script Triggers when the browser starts to load the media data
onmessage script Triggers when the message is triggered
onmousedown script Triggers when a mouse button is pressed
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The Common Gateway Interface, or CGI, is a set of standards that define how
information is exchanged between the web server and a custom script. The CGI specs are
currently maintained by the NCSA and NCSA defines CGI is as follows-The Common Gateway
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Interface, or CGI, is a standard for external gateway programs to interface with information
servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress.
To understand the concept of CGI, let’s see what happens when we click a hyper link to
browse a particular web page or URL.
Your browser contacts the HTTP web server and demand for the URL ie. filename.
Web Server will parse the URL and will look for the filename in if it finds that file
then sends back to the browser otherwise sends an error message indicating that you
have requested a wrong file.
Web browser takes response from web server and displays either the received file or
error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain
directory is requested that file is not sent back; instead it is executed as a program, and whatever
that program outputs is sent back for your browser to display. This function is called the
Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI
programs can be a PERL Script, Shell Script, C or C++ program etc.
#!/usr/bin/perl
print"Content-type:text/html\r\n\r\n";
print'<html>';
print'<head>';
print'<title>Hello Word - First CGI Program</title>';
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
print'</head>';
print'<body>';
print'<h2>Hello Word! This is my first CGI program</h2>';
print'</body>';
print'</html>';
1;
Output
All the CGI program will have access to the following environment variables. These variables
play an important role while writing any CGI program.
The method used to make the request. The most common methods are GET and
POST.
SCRIPT_FILENAME
10
The full path to the CGI script.
SCRIPT_NAME
11
The name of the CGI script.
SERVER_NAME
12
The server's hostname or IP Address.
SERVER_SOFTWARE
13
The name and version of the software the server is running.
You must have come across many situations when you need to pass some information
from your browser to web server and ultimately to your CGI Program. Most frequently browser
uses two methods two pass this information to web server. These methods are GET Method and
POST Method.
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? character as follows −
http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server
and it produces a long string that appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information to pass to the server. The GET
method has size limitation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible in your
CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any
URL or you can use HTML <FORM> tags to pass information using GET method.
4.1.4.2. Simple URL Example: Get Method
Here is a simple URL which will pass two values to hello_get.cgi program using GET
method. Below is hello_get.cgi script to handle input given by web browser.
#!/usr/bin/perl
local($buffer,@pairs, $pair, $name, $value,%FORM);
# Read in text
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
$ENV{'REQUEST_METHOD'}=~ tr/a-z/A-Z/;
if($ENV{'REQUEST_METHOD'} eq "GET"){
$buffer = $ENV{'QUERY_STRING'};
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print"Content-type:text/html\r\n\r\n";
print"<html>";
print"<head>";
print"<title>Hello - Second CGI Program</title>";
print"</head>";
print"<body>";
print"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
print"</body>";
print"</html>";
1;
Output
A generally more reliable method of passing information to a CGI program is the POST
method. This packages the information in exactly the same way as GET methods, but instead of
sending it as a text string after a ? in the URL it sends it as a separate message. This message
comes into the CGI script in the form of the standard input.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Below is hello_post.cgi script to handle input given by web browser. This script will
handle GET as well as POST method.
#!/usr/bin/perl
if($ENV{'REQUEST_METHOD'} eq "POST"){
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else{
$buffer = $ENV{'QUERY_STRING'};
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print"Content-type:text/html\r\n\r\n";
print"<html>";
print"<head>";
print"<title>Hello - Second CGI Program</title>";
print"</head>";
print"<body>";
print"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
print"</body>";
print"</html>";
1;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Simplicity
Efficiency
Security
Flexibility
Familiarity
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an
essential example, first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your
normal HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this −
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
5.3. Syntax:
The PHP parsing engine needs a way to differentiate PHP code from other elements in
the page. The mechanism for doing so is known as 'escaping to PHP'. There are four ways to do
this –
<?php...?>
If you use this style, you can be positive that your tags will always be correctly
interpreted.
<?...?>
Short tags are, as one might expect, the shortest option. You must do one of two things to
enable PHP to recognize the tags –
Set the short_open_tag setting in your php.ini file to on. This option must be disabled
to parse XML with PHP because the same syntax is used for XML tags.
ASP-style tags
ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks.
ASP-style tags look like this −
<%...%>
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
A comment is the portion of a program that exists only for the human reader and stripped
out before displaying the programs result. There are two commenting formats in PHP −
Single-line comments
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
They are generally used for short explanations or notes relevant to the local code. Here
are the examples of single line comments.
<?
# This is a comment, and
# This is the second line of the comment
Multi-lines comments
They are generally used to provide pseudocode algorithms and moredetailed explanations
when necessary. The multiline style of commenting is the same as in C. Here are the example of
multi lines comments.
<?
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
Whitespace is the stuff you type that is typically invisible on the screen, including spaces,
tabs, and carriage returns (end-of-line characters).
PHP whitespace insensitive means that it almost never matters how many whitespace
characters you have in a row.one whitespace character is the same as many such characters.
For example, each of the following PHP statements that assigns the sum of 2 + 2 to the
variable $four is equivalent −
Yeah it is true that PHP is a case sensitive language. Try out following example −
<html>
<body>
<?php
$capital =67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
Variable capital is 67
Variable CaPiTaL is
The smallest building blocks of PHP are the indivisible tokens, such as numbers
(3.14159), strings (.two.), variables ($two), constants (TRUE), and the special words that make
up the syntax of PHP itself like if, else, while, for and so forth.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Although statements cannot be combined like expressions, you can always put a
sequence of statements anywhere a statement can go by enclosing them in a set of curly braces.
Here both statements are equivalent −
if(3==2+1)
print("Good - I haven't totally lost my mind.<br>");
if(3==2+1)
{
print("Good - I haven't totally");
print("lost my mind.<br>");
}
5.5. Variables:
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
PHP does a good job of automatically converting types from one to another when
necessary.
PHP has a total of eight data types which we use to construct our variables –
Resources − are special variables that hold references to resources external to PHP
(such as database connections).
5.7. String:
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable ="name";
$literally ='My $variable will not print!\\n';
print($literally);
print"<br />";
$literally ="My $variable will print!\\n";
print($literally);
?>
There are no artificial limits on string length - within the bounds of available memory,
you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP –
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their
values.
The escape-sequence replacements are –
To concatenate two string variables together, use the dot (.) operator –
<?php
$string1="Hello World";
$string2="1234";
If we look at the code above you see that we used the concatenation operator two times.
This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty
space, to separate the two variables.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<?php
echo strlen("Hello world!");
?>
12
The length of a string is often used in loops or other functions, when it is important to
know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character
in the string)
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If
no match is found, it will return FALSE.
<?php
echo strpos("Hello world!","world");
?>
As you see the position of the string "world" in our string is position 6. The reason that it
is 6, and not 7, is that the first position in the string is 0, and not 1.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
5.8. Constants:
A constant is an identifier (name) for a simple value. The value cannot be changed during
the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Note: Unlike variables, constants are automatically global across the entire script.
Syntax
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
The example below creates a constant with a case-insensitive name:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
echo greeting;
?>
5.8.2. Constants are Global:
Constants are automatically global and can be used across the entire script.
The example below uses a constant inside a function, even if it is defined outside the
function:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Arithmetic Operators
Logical or Relational Operators
Comparison Operators
Conditional or Ternary Operators
Assignment Operators
Spaceship Operators (Introduced in PHP 7)
Array Operators
Increment/Decrement Operators
String Operators
Example
<?php
// variable 1
$x = 29;
// variable 2
$y = 4;
?>
Output
33
25
116
7.25
1
6.1.2. Logical or Relational Operators:
These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or cannot be
met so the result of a conditional statement can either be true or false. Here are the logical
operators along with their syntax and operations that PHP provides us:
AND
or Logical OR $x or $y True if either of the operand is true else false
Logical True if either of the operand is true and false if both
xor $x xor $y
XOR are true
Logical
&& $x && $y True if both the operands are true else false
AND
|| Logical OR $x || $y True if either of the operand is true else false
Logical
! !$x True if $x is false
NOT
Example
<?php
$x = 50;
$y = 30;
if ($x == 50 or $y == 20)
echo "or Success \n";
if ($x == 50 || $y == 20)
echo "|| Success \n";
if (!$z)
echo "! Success \n";
?>
Output
and Success
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
or Success
xor Success
&& Success
|| Success
! Success
6.1.3. Comparison Operators:
These operators are used to compare two elements and outputs the result in boolean form.
Here are the comparison operators along with their syntax and operations that PHP provides us:
Example
<?php
$a = 80;
$b = 50;
$c = "80";
?>
Output
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
6.1.4. Conditional or Ternary Operators:
These operators are used to compare two values and take either of the result
simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used as
shorthand notation for if…else statement that we will read in the article on decision making.
Syntax
$var = (condition)? value1 : value2;
Here, condition will either evaluate to true or false. If the condition evaluates to True, then
value1 will be assigned to the variable $var otherwise value2 will be assigned to it.
Example:
<?php
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>
Output
Example
<?php
?>
Output
75
300
60
600
20
0
6.1.6. Array Operators:
These operators are used in case of arrays. Here are the array operators along with their
syntax and operations that PHP provides us:
Example
<?php
var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Output
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
6.1.7. Increment/Decrement Operators:
These are called the unary operators as it work on single operands. These are used to
increment or decrement values.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";
$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
6.1.8. String Operators:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
<?php
$x = "AB";
$y = "c";
$z = "DE!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output
ABcDE
ABcDE
6.1.9. Spaceship Operators (Introduced in PHP 7):
PHP 7 has introduced a new kind of operator called spaceship operator (). These operators are
used to compare values but instead of returning boolean result, it returns integer values. If both the
operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is
greater, it returns 1. The following table shows how it works in detail:
Example
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<?php
$x = 50;
$y = 50;
$z = 25;
?>
Output
0
1
-1
1
1
-1
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less
than 20:
Example
<?php
$t = date("H");
if ($t <"20") {
echo"Have a good day!";
}
?>
6.2.2. The if...else Statement:
The if....else statement executes some code if a condition is true and another code if that
condition is false.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and
"Have a good night!" otherwise:
Example
<?php
$t = date("H");
if ($t <"20") {
echo"Have a good day!";
} else {
echo"Have a good night!";
}
?>
6.2.3. The if...elseif....else Statement:
The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than
10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a
good night!":
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
<?php
$t = date("H");
if ($t <"10") {
echo"Have a good morning!";
} elseif ($t <"20") {
echo"Have a good day!";
} else {
echo"Have a good night!";
}
?>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.
Example
<?php
$favcolor = "red";
switch ($favcolor){
case"red":
echo"Your favorite color is red!";
break;
case"blue":
echo"Your favorite color is blue!";
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
break;
case"green":
echo"Your favorite color is green!";
break;
default:
echo"Your favorite color is neither red, blue, nor green!";
}
?>
7.2. Loop:
Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types.
while − loops through a block of code if and as long as a specified condition is true.
do...while − loops through a block of code once, and then repeats the loop as long as
a special condition is true.
We will discuss about continue and break keywords used to control the loops execution.
The for statement is used when you know how many times you want to execute a
statement or a block of statements.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Syntax
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop −
<html>
<body>
<?php
$a =0;
$b =0;
</body>
</html>
The while statement will execute a block of code if and as long as a test expression is
true.
If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until the test
expression is found to be false.
Syntax
while (condition) {
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i =0;
$num =50;
while( $i <10){
$num--;
$i++;
}
</body>
</html>
The do...while statement will execute a block of code at least once - it then will repeat the
loop as long as a condition is true.
Syntax
do {
code to be executed;
}
while (condition);
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
<html>
<body>
<?php
$i =0;
$num =0;
do{
$i++;
}
while( $i <10);
echo ("Loop stopped at i = $i");
?>
</body>
</html>
Loop stopped at I = 10
The for-each statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one and in the next
pass next element will be processed.
Syntax
Example
<html>
<body>
<?php
$array = array(1,2,3,4,5);
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
7.3.PHP function:
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value.
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you –
In fact you hardly need to create your own PHP function because there are already more
than 1000 of built-in library functions created for different area and you just need to call them
according to your requirement.
It’s very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will call it.
Following example creates a function called writeMessage() and then calls it just after creating
it.
Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example below −
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage(){
echo "You are really a nice person, Have a nice time!";
}
</body>
</html>
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function. Following
example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result –
<html>
<head>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result −
Original Value is 10
Original Value is 16
7.3.4. PHP Functions returning value:
A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns
their sum to the calling program.
Note that return keyword is used to return a value from a function.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2){
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10,20);
</body>
</html>
Numeric array − an array with a numeric index. Values are stored and accessed in
linear fashion.
Associative array − an array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array − an array containing one or more arrays and values are
accessed using multiple indices.
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array(1,2,3,4,5);
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Value is one
Value is two
Value is three
Value is four
Value is five
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad"=>2000,"qadir"=>1000,"zara"=>500);
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in
three subjects −
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad"=> array (
"physics"=>35,
"maths"=>30,
"chemistry"=>39
),
"qadir"=> array (
"physics"=>30,
"maths"=>32,
"chemistry"=>29
),
"zara"=> array (
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
"physics"=>31,
"maths"=>22,
"chemistry"=>39
)
);
</body>
</html>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr ="";
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(empty($_POST["name"])){
$nameErr ="Name is required";
}else{
$name = test_input($_POST["name"]);
}
if(empty($_POST["email"])){
$emailErr ="Email is required";
}else{
$email = test_input($_POST["email"]);
if(empty($_POST["course"])){
$course ="";
}else{
$course = test_input($_POST["course"]);
}
if(empty($_POST["class"])){
$class ="";
}else{
$class = test_input($_POST["class"]);
}
if(empty($_POST["gender"])){
$genderErr ="Gender is required";
}else{
$gender = test_input($_POST["gender"]);
}
if(empty($_POST["subject"])){
$subjectErr ="You must select 1 or more";
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
}else{
$subject = $_POST["subject"];
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<tr>
<td>E-mail: </td>
<td><inputtype="text"name="email">
<spanclass="error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td>Time:</td>
<td><inputtype="text"name="course">
<spanclass="error"><?php echo $websiteErr;?></span>
</td>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
</tr>
<tr>
<td>Classes:</td>
<td><textareaname="class"rows="5"cols="40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<inputtype="radio"name="gender"value="female">Female
<inputtype="radio"name="gender"value="male">Male
<spanclass="error">* <?php echo $genderErr;?></span>
</td>
</tr>
<tr>
<td>Select:</td>
<td>
<selectname="subject[]"size="4"multiple>
<optionvalue="Android">Android</option>
<optionvalue="Java">Java</option>
<optionvalue="C#">C#</option>
<optionvalue="Data Base">Data Base</option>
<optionvalue="Hadoop">Hadoop</option>
<optionvalue="VB script">VB script</option>
</select>
</td>
</tr>
<tr>
<td>Agree</td>
<td><inputtype="checkbox"name="checked"value="1"></td>
<?php if(!isset($_POST['checked'])){?>
<spanclass="error">* <?php echo "You must agree to terms";?></span>
<?php }?>
</tr>
<tr>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<td>
<inputtype="submit"name="submit"value="Submit">
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your given values are as :</h2>";
echo ("<p>Your name is $name</p>");
echo ("<p> your email address is $email</p>");
echo ("<p>Your class time at $course</p>");
echo ("<p>your class info $class </p>");
echo ("<p>your gender is $gender</p>");
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role
of a user interface for a Java web application. Web developers write JSPs as text files that
combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.
JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offers several advantages in comparison with the
CGI.
Performance is significantly better because JSP allows embedding Dynamic
Elements in HTML Pages itself instead of having separate CGI files.
JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.
Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI,
EJB, JAXP, etc.
JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.
Following table lists out the other advantages of using JSP over other technologies −
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is
portable to other operating systems and non-Microsoft Web servers.
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use of
Apache which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
application.
As with a normal page, your browser sends an HTTP request to the web server.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements the
corresponding dynamic behaviour of the page.
The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format. The output is
further passed on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static
HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram –
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated
servlet still matches the JSP's contents. This makes the process more efficient than with the other
scripting languages (such as PHP) and therefore faster.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
So in a way, a JSP page is really just another way to write a servlet without having to be a
Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a
regular servlet.
Lecture 2: JSP Servers, JSP Life Cycle, JSP Page Creation and
Execution
2.1. JSP Servers:
If you do not have a JSP capable web-server or application server, the first step is to
download one. There are many such servers available, most of which can be downloaded for
free evaluation and/or development. Some of them are:
Blazix from Desiderata Software (1.5 Megabytes, JSP, Servlets and EJBs)
TomCat from Apache (Approx 6 Megabytes)
WebLogic from BEA Systems (Approx 40 Megabytes, JSP, Servlets and EJBs)
WebSphere from IBM (Approx 100 Megabytes, JSP, Servlets and EJBs)
Apache Tomcat is an open source software implementation of the JavaServer Pages and
Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be
integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine –
Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or
/usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME
environment variable pointing to these locations.
Tomcat can be started by executing the following commands on the Windows machine –
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on the Unix (Solaris, Linux,
etc.) machine –
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web-applications included with Tomcat will be
available by visiting http://localhost:8080/.
Upon execution, you will receive the following output –
Tomcat can be stopped by executing the following commands on the Windows machine
−
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on UNIX (Solaris, Linux,
etc.) machine −
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
2.2. JSP Life Cycle:
A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
2.2.1. Paths Followed By JSP:
The following are the paths followed by a JSP –
Compilation
Initialization
Execution
Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The
four phases have been described below –
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The destruction phase of the JSP life cycle represents when a JSP is being removed from
use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing database
connections or closing open files.
The jspDestroy() method has the following form –
public void jspDestroy() {
// Your cleanup code goes here.
}
2.3. Creating a simple JSP Page:
To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code
in the JSP page. We will learn scriptlet tag later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
It will print 10 on the browser.
scriptlet tag
expression tag
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
declaration tag
</body>
</html>
3.1.2.JSP expression tag:
The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable or
method.
Syntax
<%= statement %>
Example
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag.
Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the instance
of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html
file gets the username and sends the request to the welcome.jsp file, which displays the
username.
File: index.html
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
3.1.3.JSP Declaration Tag:
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service () method of
auto generated servlet.
So it doesn't get memory at each request.
Syntax
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
3.1.3.1. Difference between JSP scriptlet tag and declaration tag:
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
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method
In this example of JSP declaration tag, we are defining the method which returns the cube
of given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
3.2. JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out", a part of your JSP page.
Following is the syntax of the JSP comments –
<%-- This is JSP comment --%>
Following example shows the JSP Comments –
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
A Test of Comments
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary –
<body>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<% } %>
</body>
</html>
The above code will generate the following result –
Today is not weekend
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside scriptlets –
<%! int day = 3; %>
<html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
</html>
The above code will generate the following result –
It's Wednesday.
3.3.2. Loop Statements:
You can also use three basic types of looping blocks in Java: for, while, and do…while
blocks in your JSP programming.
Let us look at the following for loop example –
<%! int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body>
</html>
The above code will generate the following result –
JSP Tutorial
JSP Tutorial
JSP Tutorial
Above example can be written using the while loop as follows –
<%! int fontSize; %>
<html>
<head><title>WHILE LOOP Example</title></head>
<body>
<%while ( fontSize <= 3){ %>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
JSP Tutorial
JSP Tutorial
3.4. JSP Operators:
JSP supports all the logical and arithmetic operators supported by Java. Following table
lists out all the operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
page directive
include directive
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
taglib directive
Syntax
<%@ directive attribute="value" %>
5.1.1. JSP page directive:
The page directive defines attributes that apply to an entire JSP page.
Syntax
<%@ page attribute="value" %>
5.1.1.1. Attributes of JSP page directive:
import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage
<mytag:currentDate/>
</body>
</html>
5.2. JSP Action Tags:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The JSP
action tags are given below.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for JavaBean development.
The jsp:forward action tag is used to forward the request to another resource it may be
jsp, html or another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag without parameter
In this example, we are simply forwarding the request to the printdate.jsp file.
index.jsp
<html>
<body>
<h2>this is index page</h2>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
</body>
</html>
printdate.jsp
<html>
<body>
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
6.1.3. Accessing JavaBeans:
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean
becomes a scripting variable that can be accessed by both scripting elements and other custom
tags used in the JSP. The full syntax for the useBean tag is as follows –
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based
on your requirement. The value of the id attribute may be any value as a long as it is a unique
name among other useBean declarations in the same JSP.
Following example shows how to use the useBean action –
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010
6.1.4. Accessing JavaBeans Properties:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to
access the get methods and the <jsp:setProperty/> action to access the set methods. Here is the
full syntax –
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by
the useBean action. The property attribute is the name of the get or the setmethods that should be
invoked.
Following example shows how to access the data using the above syntax –
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP.
The following result will be displayed –
Student First Name: Zara
Student Age: 10
application. In fact, layout managers demonstrate an example of one of the tenets of object-
oriented design: encapsulate the concept that varies, which is also a fundamental theme for many
design patterns.
JSP does not provide direct support for encapsulating layout, so Webpages with identical
formats usually replicate layout code; for example, the following figure shows a Webpage
containing header, footer, sidebar, and main content sections.
Webpage layout
The layout of the page shown in the above figure is implemented with HTML table tags:
Example 1. Including content
<html><head><title>JSP Templates</title></head>
<body background='graphics/background.jpg'>
<table>
<tr valign='top'><td><%@include file='sidebar.html'%></td>
<td><table>
<tr><td><%@include file='header.html'%></td></tr>
<tr><td><%@include file='introduction.html'%></td></tr>
<tr><td><%@include file='footer.html'%></td></tr>
</table>
</td>
</tr>
</table>
</body></html>
In the example listed above, content is included with the JSP include directive, which
allows the content of the page to vary -- by changing the included files -- without modifying the
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
page itself. However, because layout is hard coded, layout changes require modifications to the
page. If a Website has multiple pages with identical formats, which is common, even simple
layout changes require modifications to all of the pages.
To minimize the impact of layout changes, we need a mechanism for including layout in
addition to content; that way, both layout and content can vary without modifying files that use
them. That mechanism is JSP templates.
7.1. Using templates:
Templates are JSP files that include parameterized content. The templates discussed in
this article are implemented with a set of custom tags: template:get, template:put, and
template:insert. The template:get tag accesses parameterized content, as illustrated in Example
2.a, which produces Webpages with the format shown in the above figure.
Example 2.a. A template
<%@ taglib uri='/WEB-INF/tlds/template.tld' prefix='template' %>
<html><head><title><template:get name='title'/></title></head>
<body background='graphics/background.jpg'>
<table>
<tr valign='top'><td><template:get name='sidebar'/></td>
<td><table>
<tr><td><template:get name='header'/></td></tr>
<tr><td><template:get name='content'/></td></tr>
<tr><td><template:get name='footer'/></td></tr>
</table>
</td>
</tr>
</table>
</body></html>
Example 2.a is nearly identical to Example 1, except we use template:get instead of the
include directive. Let's examine how template:get works.
template:get retrieves a Java bean with the specified name from request scope. The bean
contains the URI (Uniform Resource Identifier) of a Web component that's included by
template:get. For example, in the template listed in Example 2.a, template:get obtains a URI --
header.html -- from a bean named header in request scope. Subsequently, template:get includes
header.html.
template:put puts the beans in request scope that are subsequently retrieved by
template:get. The template is included with template:insert. Example 2.b illustrates the use of the
put and insert tags:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Note: JSP provides two ways to include content: statically, with the include directive, and
dynamically, with the include action. The include directive includes the source of the target page
at compile time and is equivalent to C's #include or Java's import. The include action includes
the target's response generated at runtime.
Like the JSP include action, templates include content dynamically. So, although the JSP
pages in Example 1 and Example 2.b are functionally identical, the former statically includes
content, whereas the latter dynamically includes it.
7.2. Optional content:
All template content is optional, which makes a single template useful to more
Webpages. For example, the following two figures show two pages -- login and inventory -- that
use the same template. Both pages have a header, footer, and main content. The inventory page
has an edit panel (which the login page lacks) for making inventory changes.
The inventory page uses the template listed above and specifies content for the edit panel:
<%@ taglib uri='template.tld' prefix='template' %>
<%@ taglib uri='security.tld' prefix='security' %>
<template:insert template='/template.jsp'>
...
<template:put name='editPanel'
content='/editPanelContent.jsp'/>
...
</template:insert>
In contrast, the login page does not specify content for the edit panel:
<%@ taglib uri='template.tld' prefix='template' %>
<template:insert template='/template.jsp'>
<template:put name='title' content='Login' direct='true'/>
<template:put name='header' content='/header.jsp'/>
<template:put name='main-content'
content='/login.jsp'/>
<template:put name='footer' content='/footer.jsp'/>
</template:insert>
Because the login page does not specify content for the edit panel, it's not included.
7.3. Role-based content:
Web applications often discriminate content based on a user's role. For example, the same
JSP template, which includes the edit panel only when the user's role is curator, produces the two
pages shown in the following two figures.
template:insert
template:put
template:get
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The insert tag includes a template, but before it does, put tags store information -- a
name, URI, and Boolean value specifying whether content should be included or printed directly
-- about the content the template includes. template:get, which includes (or prints) the specified
content, subsequently accesses the information.
template:put stores beans in request scope but not directly because if two templates use
the same content names, a nested template could overwrite the enclosing template's content.
To ensure that each template has access only to its own information, template:insert
maintains a stack of hashtables. Each insert start tag creates a hashtable and pushes it on the
stack. The enclosed put tags create beans and store them in the newly created hashtable.
Subsequently, get tags in the included template access the beans in the hashtable. The following
figure shows how the stack is maintained for nested templates.
import java.util.Stack;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
public class InsertTag extends TagSupport {
private String template;
private Stack stack;
// setter method for template attribute
public void setTemplate(String template) {
this.template = template;
}
public int doStartTag() throws JspException {
stack = getStack(); // obtain a reference to the template stack
stack.push(new Hashtable()); // push new hashtable onto stack
return EVAL_BODY_INCLUDE; // pass tag body through unchanged
}
public int doEndTag() throws JspException {
try {
pageContext.include(template); // include template
}
catch(Exception ex) { // IOException or ServletException
throw new JspException(ex.getMessage()); // recast exception
}
stack.pop(); // pop hashtable off stack
return EVAL_PAGE; // evaluate the rest of the page after the tag
}
// tag handlers should always implement release() because
// handlers can be reused by the JSP container
public void release() {
template = null;
stack = null;
}
public Stack getStack() {
// try to get stack from request scope
Stack s = (Stack)pageContext.getAttribute(
"template-stack",
PageContext.REQUEST_SCOPE);
// if the stack's not present, create a new one and
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
package beans.templates;
public class PageParameter {
private String content, direct;
public void setContent(String s) {content = s; }
public void setDirect(String s) { direct = s; }
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
databases in SQL Server, including the directory source name (DSN), directory, driver of the
database, and the ID and password of the user.
1. In Windows Explorer, navigate to C:\Windows\sysWOW64\.
2. Double-click odbcad32.exe.
The ODBC Data Source Administrator dialog box appears.
3. Click the System DSN tab.
4. Click Add.
The Create New Data Source dialog box appears.
5. Scroll down through the list and select SQL Server, and then click Finish.
The Create a New Data Source to SQL Server wizard appears.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
6. In Name and Description, type the name and a description for the ODBC data source
you are creating.
Example: ODBC data source
7. From Server, select the name of the SQL server where your database software exists.
Caution: Include the full name of the SQL instance where the database software
exists.
Example: SERVER1\SQLEXPRESS
8. Click Next >.
The next screen of the Create a New Data Source to SQL Server wizard appears.
9. Define which SQL Server login credentials to use in one of the following ways:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
11. Select Change the default database to, and then choose the name of your database
from the menu below it.
Warning: Do not change any of the other settings on this screen of the wizard.
12. Click Next >.
The next screen of the Create a New Data Source to SQL Server wizard appears.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs)
All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
8.2.1. JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers –
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application –
Statement: You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.
ResultSet: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
SQLException: This class handles any errors that occur in a database application.
}
finally {
...
}
Once you've created a Statement object, you can then use it to execute an SQL statement
with one of its three execute methods.
boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements
or when you need to use truly dynamic SQL.
int executeUpdate (String SQL): Returns the number of rows affected by the execution
of the SQL statement. Use this method to execute SQL statements for which you expect
to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE
statement.
ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.
Closing Statement Object
Just as you close a Connection object to save database resources, for the same reason you
should also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object
first, it will close the Statement object as well. However, you should always explicitly close the
Statement object to ensure proper cleanup.
The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
All parameters in JDBC are represented by the ? symbol, which is known as the
parameter marker. You must supply values for every parameter before executing the SQL
statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java
data type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive a SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array indices,
which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However,
the methods are modified to use SQL statements that can input the parameters.
Closing PreparedStatement Object
Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object
first, it will close the PreparedStatement object as well. However, you should always explicitly
close the PreparedStatement object to ensure proper cleanup.
PreparedStatement pstmt = null;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}
8.2.3.3. The CallableStatement Objects:
Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database stored
procedure.
Creating CallableStatement Object
Suppose, you need to execute the following Oracle stored procedure −
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
NOTE: Above stored procedure has been written for Oracle, but we are working with
MySQL database so, let us write same stored procedure for MySQL as follows to create it in
EMP database –
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
END $$
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object
only uses the IN parameter. The CallableStatement object can use all the three.
Here are the definitions of each –
Parameter Description
A parameter whose value is unknown when the SQL statement is created.
IN
You bind values to IN parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns. You
OUT
retrieve values from theOUT parameters with the getXXX() methods.
A parameter that provides both input and output values. You bind variables
INOUT with the setXXX() methods and retrieve values with the getXXX()
methods.
The following code snippet shows how to employ the Connection.prepareCall() method to
instantiate a CallableStatement object based on the preceding stored procedure –
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
The String variable SQL, represents the stored procedure, with parameter placeholders.
Using the CallableStatement objects is much like using the PreparedStatement objects.
You must bind values to all the parameters before executing the statement, or you will receive an
SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type you
are binding.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the
JDBC data type, to the data type that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter
with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object
first, it will close the CallableStatement object as well. However, you should always explicitly
close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}
Lecture 9: Java Servlet Environment and Role, Servlet life cycle
9.1. Servlet Environment and Role:
Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Servlets execute within the address space of a Web server. It is not necessary to
create a separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
9.2. Servlets Architecture:
The following diagram shows the position of Servlets in a Web Application.
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as with the
init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
The init method definition looks like this –
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method –
The service () method is called by the container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML form that has
no METHOD specified and it should be handled by doGet() method.
A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this –
Architecture Diagram
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Sample Code
Following is the sample source code structure of a servlet example to show Hello World
−
}
}
Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this
file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location must
be added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and compile
HelloWorld.java as follows –
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work properly, you
have to include the location of the Java SDK that you are using in the PATH environment
variable.
If everything goes fine, above compilation would produce HelloWorld.classfile in the
same directory. Next section would explain how a compiled servlet would be deployed in
production.
Servlet Deployment
By default, a servlet application is located at the path
<Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into
<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml
file. There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or
<Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine,
you would get the following result.
method if you have password or other sensitive information to pass to the server. The GET
method has size limitation: only 1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and will be accessible
through QUERY_STRING environment variable and Servlet handles this type of requests using
doGet() method.
10.2. POST Method:
A generally more reliable method of passing information to a backend program is the
POST method. This packages the information in exactly the same way as GET method, but
instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate
message. This message comes to the backend program in the form of the standard input which
you can parse and use for your processing. Servlet handles this type of requests using doPost()
method.
10.3. Reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending
on the situation −
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next you
would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your
browser's Location:box and make sure you already started tomcat server, before firing above
command in the browser. This would generate following result –
</body>
</html>
Keep this HTML in a file Hello.htm and put it in
<Tomcat-installationdirectory>/webapps/ROOT directory. When you would
accesshttp://localhost:8080/Hello.htm, here is the actual output of the above form.
Try to enter First Name and Last Name and then click submit button to see the result on
your local machine where tomcat is running. Based on the input provided, it will generate similar
result as mentioned in the above example.
10.6. POST Method Example Using Form:
Let us do little modification in the above servlet, so that it can handle GET as well as
POST methods. Below is HelloForm.java servlet program to handle input given by web browser
using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the POST
method as follows −
<html>
<body>
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then
click submit button to see the result on your local machine where tomcat is running.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Based on the input provided, it would generate similar result as mentioned in the above
examples.
10.7. Passing Checkbox Data to Servlet Program:
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action = "CheckBox" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" />
Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
The result of this code is the following form
Given below is the CheckBox.java servlet program to handle input given by web browser
for checkbox button.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>Maths Flag : </b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
For the above example, it would display following result –
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
}
}
out.println("</tr>\n</table>\n</body></html>");
}
doGet(request, response);
}
}
Now, try the above servlet with the following form −
<html>
<body>
<form action = "ReadParams" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
Now calling servlet using the above form would generate the following result –
You can try the above servlet to read any other form's data having other objects like text
box, radio button or drop down box etc.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
after the specified date. The server sends a code, 304 which means Not
Modified header if no newer result is available.
If-Unmodified-Since
11 This header is the reverse of If-Modified-Since; it specifies that the operation
should succeed only if the document is older than the specified date.
Referer
This header indicates the URL of the referring Web page. For example, if you are
12
at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is
included in the Referrer header when the browser requests Web page 2.
User-Agent
13 This header identifies the browser or other client making the request and can be
used to return different content to different types of browsers.
There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object.
Returns the part of this request's URL from the protocol name up to the query
string in the first line of the HTTP request.
String getRequestedSessionId()
24
Returns the session ID specified by the client.
String getServletPath()
25
Returns the part of this request's URL that calls the JSP.
String[] getParameterValues(String name)
26 Returns an array of String objects containing all of the values the given request
parameter has, or null if the parameter does not exist.
boolean isSecure()
27 Returns a Boolean indicating whether this request was made using a secure
channel, such as HTTPS.
int getContentLength()
28 Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known.
int getIntHeader(String name)
29
Returns the value of the specified request header as an int.
int getServerPort()
30
Returns the port number on which this request was received.
Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using hasMoreElements() method to determine when to stop and using nextElement()
method to get each parameter name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
doGet(request, response);
}
}
Now calling the above servlet would generate the following result –
accept */*
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code
(200 in the example), and a very short message corresponding to the status code (OK in the
example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to
the browser from web server side and you would use them very frequently in web programming
–
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
8 This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
Expires
9 This header specifies the time at which the content should be considered out-of-
date and thus no longer be cached.
Last-Modified
This header indicates when the document was last changed. The client can then
10
cache the document and supply a date by an If-Modified-Since request header
in later requests.
Location
This header should be included with all responses that have a status code in the
11
300s. This notifies the browser of the document address. The browser
automatically reconnects to this location and retrieves the new document.
Refresh
This header specifies how soon the browser should ask for an updated page.
12
You can specify time in number of seconds after which a page would be
refreshed.
Retry-After
13 This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
}
doGet(request, response);
}
}
Now calling the above servlet would display current system time after every 5 seconds as
follows. Just run the servlet and wait to see the result –
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
This lecture will teach you how to set or reset cookies, how to access them and how to
delete them.
11.1.1. The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A servlet that sets a cookie might send headers that look something like
this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
`As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server. The browser's headers might look something like
this −
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = xyz
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
A servlet will then have access to the cookie through the request method
request.getCookies() which returns an array of Cookie objects.
11.1.2. Servlet Cookies Methods:
Following is the list of useful methods which you can use while manipulating cookies in
servlet.
out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +
"</body>
</html>"
);
}
}
Compile the above servlet HelloForm and create appropriate entry in web.xml file and
finally try following HTML page to call servlet.
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Keep above HTML content in a file Hello.htm and put it in <Tomcat-
installationdirectory>/webapps/ROOT directory. When you would access
http://localhost:8080/Hello.htm, here is the actual output of the above form.
Try to enter First Name and Last Name and then click submit button. This would display
first name and last name on your screen and same time it would set two cookies firstName and
lastName which would be passed back to the server when next time you would press Submit
button.
Next section would explain you how you would access these cookies back in your web
application.
11.1.4. Reading Cookies with Servlet:
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by
calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use
getName() and getValue() methods to access each cookie and associated value.
Example
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
Example
The following example would delete and existing cookie named "first_name" and when
you would run ReadCookies servlet next time it would return null value for first_name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie
as follows –
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and
select Internet Options. To delete all cookies, press Delete Cookies.
11.2.1. Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a cookie,
so I would not recommend to use this procedure to maintain the sessions.
11.2.2. Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as
follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular
(<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.
11.2.3. URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and
the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session
identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the
client.
URL rewriting is a better way to maintain sessions and it works even when browsers
don't support cookies. The drawback of URL re-writing is that you would have to generate every
URL dynamically to assign a session ID, even in case of a simple static HTML page.
11.2.4. The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface
which provides a way to identify a user across more than one page request or visit to a Web site
and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and
an HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below –
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
This example describes how to use the HttpSession object to find out the creation time
and the last-accessed time for a session. We would associate a new session with the request if
one does not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
}
session.setAttribute(visitCountKey, visitCount);
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td>
</tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime + " </td>
</tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime + " </td>
</tr>\n" +
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID + " </td>
</tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td>
</tr>\n" +
"</table>\n" +
"</body>
</html>"
);
}
}
Compile the above servlet SessionTrack and create appropriate entry in web.xml file.
Now running http://localhost:8080/SessionTrack would display the following result when you
would run for the first time –
Now try to run the same servlet for second time, it would display following result.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that
session in seconds. So if your session is configured in web.xml for 15 minutes,
getMaxInactiveInterval( ) returns 900.
History
ASP.NET 1.0 was released on January 5, 2002, as part of .Net Framework version 1.0. At
that time, it was easy to think of ASP.NET and Web Forms as one and the same thing. ASP.NET
has however always supported two layers of abstraction −
System.Web.UI − The Web Forms layer, comprising server controls, ViewState, and
so on.
System.Web − It supplies the basic web stack, including modules, handlers, the
HTTP stack, etc.
By the time ASP.NET MVC was announced in 2007, the MVC pattern was becoming
one of the most popular ways of building web frameworks.
In April 2009, the ASP.NET MVC source code was released under the Microsoft Public
License (MS-PL). "ASP.NET MVC framework is a lightweight, highly testable presentation
framework that is integrated with the existing ASP.NET features.
Some of these integrated features are master pages and membership-based authentication.
The MVC framework is defined in the System.Web.Mvc assembly.
In March 2012, Microsoft had released part of its web stack (including ASP.NET MVC,
Razor and Web API) under an open source license (Apache License 2.0). ASP.NET Web Forms
was not included in this initiative.
Why ASP.NET MVC?
Microsoft decided to create their own MVC framework for building web applications.
The MVC framework simply builds on top of ASP.NET. When you are building a web
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
application with ASP.NET MVC, there will be no illusions of state, there will not be such a thing
as a page load and no page life cycle at all, etc.
Another design goal for ASP.NET MVC was to be extensible throughout all aspects of
the framework. So when we talk about views, views have to be rendered by a particular type of
view engine. The default view engine is still something that can take an ASPX file. But if you
don't like using ASPX files, you can use something else and plug in your own view engine.
There is a component inside the MVC framework that will instantiate your controllers.
You might not like the way that the MVC framework instantiates your controller, you might
want to handle that job yourself. So, there are lots of places in MVC where you can inject your
own custom logic to handle tasks.
The whole idea behind using the Model View Controller design pattern is that you
maintain a separation of concerns. Your controller is no longer encumbered with a lot of ties to
the ASP.NET runtime or ties to the ASPX page, which is very hard to test. You now just have a
class with regular methods on it that you can invoke in unit tests to find out if that controller is
going to behave correctly.
Benefits of ASP.NET MVC
Following are the benefits of using ASP.NET MVC −
Makes it easier to manage complexity by dividing an application into the model, the
view, and the controller.
Enables full control over the rendered HTML and provides a clean separation of
concerns.
Direct control over HTML also means better accessibility for implementing
compliance with evolving Web standards.
Facilitates adding more interactivity and responsiveness to existing apps.
Provides better support for test-driven development (TDD).
Works well for Web applications that are supported by large teams of developers and
for Web designers who need a high degree of control over the application behavior.
12.2. ASP.NET MVC – Architecture:
The MVC (Model-View-Controller) design pattern has actually been around for a few
decades, and it's been used across many different technologies. Everything from Smalltalk to C+
+ to Java, and now C Sharp and .NET use this design pattern to build a user interface.
Following are some salient features of the MVC pattern −
The Model − A set of classes that describes the data you are working with as well as
the business logic.
The View − Defines how the application’s UI will be displayed. It is a pure HTML,
which decides how the UI is going to look like.
The Controller − A set of classes that handles communication from the user, overall
application flow, and application-specific logic.
Idea behind MVC
The idea is that you'll have a component called the view, which is solely responsible for
rendering this user interface whether that be HTML or whether it actually be UI widgets on a
desktop application.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The view talks to a model, and that model contains all of the data that the view needs to
display. Views generally don't have much logic inside of them at all.
In a web application, the view might not have any code associated with it at all. It might
just have HTML and then some expressions of where to take pieces of data from the model and
plug them into the correct places inside the HTML template that you've built in the view.
The controller that organizes is everything. When an HTTP request arrives for an MVC
application, that request gets routed to a controller, and then it's up to the controller to talk to
either the database, the file system, or the model.
12.3. ASP.NET MVC - Getting Started:
In this lecture, we will look at a simple working example of ASP.NET MVC. We will be
building a simple web app here. To create an ASP.NET MVC application, we will use Visual
Studio 2015, which contains all of the features you need to create, test, and deploy an MVC
Framework application.
Create ASP.Net MVC Application
Following are the steps to create a project using project templates available in Visual
Studio.
Step 1
Open the Visual Studio. Click File → New → Project menu option.
Step 2
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 5
To keep things simple, select the ‘Empty’ option and check the MVC checkbox in the
Add folders and core references section. Click Ok.
It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio, you will see a number of files and folders
displayed in the Solution Explorer window.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
As you know that we have created ASP.Net MVC project from an empty project
template, so for the moment the application does not contain anything to run.
Step 6
Run this application from Debug → Start Debugging menu option and you will see a 404
Not Found Error.
The default browser is, Internet Explorer, but you can select any browser that you have
installed from the toolbar.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Add Controller
To remove the 404 Not Found error, we need to add a controller, which handles all the
incoming requests.
Step 1
To add a controller, right-click on the controller folder in the solution explorer and select
Add → Controller.
Step 2
Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.o
Step 3
Set the name to HomeController and click the Add button.
You will see a new C# file HomeController.cs in the Controllers folder, which is open for
editing in Visual Studio as well.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 4
To make this a working example, let’s modify the controller class by changing the action
method called Index using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFirstApp.Controllers {
public class HomeController : Controller {
// GET: Home
public string Index(){
return "Hello World, this is ASP.Net MVC Tutorials";
}
}
}
Step 5
Run this application and you will see that the browser is displaying the result of the Index
action method.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The MVC framework handles converting the route data into a concrete controller that can
handle requests. After the controller has been created, the next major step is Action Execution. A
component called the action invoker finds and selects an appropriate Action method to invoke
the controller.
After our action result has been prepared, the next stage triggers, which is Result
Execution. MVC separates declaring the result from executing the result. If the result is a view
type, the View Engine will be called and it's responsible for finding and rending our view.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
If the result is not a view, the action result will execute on its own. This Result Execution
is what generates an actual response to the original HTTP request.
12.5. ASP.NET MVC - Routing:
Routing is the process of directing an HTTP request to a controller and the functionality
of this processing is implemented in System.Web.Routing. This assembly is not part of
ASP.NET MVC. It is actually part of the ASP.NET runtime, and it was officially released with
the ASP.NET as a .NET 3.5 SP1.
System.Web.Routing is used by the MVC framework, but it's also used by ASP.NET
Dynamic Data. The MVC framework leverages routing to direct a request to a controller. The
Global.asax file is that part of your application, where you will define the route for your
application.
This is the code from the application start event in Global.asax from the MVC App which
we created in the previous lecture.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start(){
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
Following is the implementation of RouteConfig class, which contains one method
RegisterRoutes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new{ controller = "Home", action = "Index", id =
UrlParameter.Optional});
}
}
}
You will define the routes and those routes will map URLs to a specific controller action.
An action is just a method on the controller. It can also pick parameters out of that URL and pass
them as parameters into the method.
So this route that is defined in the application is the default route. As seen in the above
code, when you see a URL arrive in the form of (something)/(something)/(something), then the
first piece is the controller name, second piece is the action name, and the third piece is an ID
parameter.
12.5.1. Understanding Routes:
MVC applications use the ASP.NET routing system, which decides how URLs map to
controllers and actions.
When Visual Studio creates the MVC project, it adds some default routes to get us
started. When you run your application, you will see that Visual Studio has directed the browser
to port 63664. You will almost certainly see a different port number in the URL that your
browser requests because Visual Studio allocates a random port when the project is created.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
In the last example, we have added a HomeController, so you can also request any of the
following URLs, and they will be directed to the Index action on the HomeController.
http://localhost:63664/Home/
http://localhost:63664/Home/Index
When a browser requests http://mysite/ or http://mysite/Home, it gets back the output
from HomeController’s Index method.
You can try this as well by changing the URL in the browser. In this example, it is
http://localhost:63664/, except that the port might be different.
If you append /Home or /Home/Index to the URL and press ‘Enter’ button, you will see
the same result from the MVC application.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
As you can see in this case, the convention is that we have a controller called
HomeController and this HomeController will be the starting point for our MVC application.
The default routes that Visual Studio creates for a new project assumes that you will
follow this convention. But if you want to follow your own convention then you would need to
modify the routes.
12.5.2. Custom Convention:
You can certainly add your own routes. If you don't like these action names, if you have
different ID parameters or if you just in general have a different URL structure for your site, then
you can add your own route entries.
Let’s take a look at a simple example. Consider we have a page that contains the list of
processes. Following is the code, which will route to the process page.
routes.MapRoute(
"Process",
"Process/{action}/{id}",
defaults: new{
controller = "Process", action = "List ", id = UrlParameter.Optional}
);
When someone comes in and looks for a URL with Process/Action/Id, they will go to the
Process Controller. We can make the action a little bit different, the default action, we can make
that a List instead of Index.
Now a request that arrives looks like localhosts/process. The routing engine will use this
routing configuration to pass that along, so it's going to use a default action of List.
Following is the complete class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCFirstApp{
public class RouteConfig{
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
routes.MapRoute(
"Process", "Process/{action}/{id}",
defaults: new{
controller = " Process", action = "List ", id =
UrlParameter.Optional});
routes.MapRoute(
name: "Default", url: "{controller}/{action}/{id}",
defaults: new{
controller = "Home", action = "Index", id =
UrlParameter.Optional});
}
}
}
Step 1
Run this and request for a process page with the following URL
http://localhost:63664/Process
You will see an HTTP 404, because the routing engine is looking for ProcessController,
which is not available.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 2
Create ProcessController by right-clicking on Controllers folder in the solution explorer
and select Add → Controller.
Step 3
Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 4
Set the name to ProcessController and click ‘Add’ button.
Now you will see a new C# file ProcessController.cs in the Controllers folder, which is
open for editing in Visual Studio as well.
Now our default action is going to be List, so we want to have a List action here instead
of Index.
Step 5
Change the return type from ActionResult to string and also return some string from this
action method using the following code.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFirstApp.Controllers{
public class ProcessController : Controller{
// GET: Process
public string List(){
return "This is Process page";
}
}
}
Step 6
When you run this application, again you will see the result from the default route. When
you specify the following URL, http://localhost:63664/Process/List, then you will see the result
from the ProcessController.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 2
From the left pane, select Templates → Visual C# → Web.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 3
In the middle pane, select ASP.NET Web Application.
Step 4
Enter the project name ‘MVCControllerDemo’ in the Name field and click ok to
continue. You will see the following dialog, which asks you to set the initial content for the
ASP.NET project.
Step 5
To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add
folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio you will see a number of files and folders
displayed in the Solution Explorer window.
Since we have created ASP.Net MVC project from an empty project template, so at the
moment, the application does not contain anything to run.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 6
Add EmployeeController by right-clicking on Controllers folder in the solution explorer.
Select Add → Controller.
Step 7
Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8
Set the name to EmployeeController and click ‘Add’ button.
You will see a new C# file EmployeeController.cs in the Controllers folder, which is
open for editing in Visual Studio as well.
Now, in this application we will add a custom route for Employee controller with the
default Route.
Step 1
Go to “RouteConfig.cs” file under “App_Start” folder and add the following route.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
routes.MapRoute(
"Employee", "Employee/{name}", new{
controller = "Employee", action = "Search", name =
UrlParameter.Optional });
Following is the complete implementation of RouteConfig.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCControllerDemo {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Employee", "Employee/{name}", new{
controller = "Employee", action = "Search", name = UrlParameter.Optional });
routes.MapRoute(
name: "Default", url: "{controller}/{action}/{id}", defaults: new{
controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
}
Consider a scenario wherein any user comes and searches for an employee, specifying the
URL “Employee/Mark”. In this case, Mark will be treated as a parameter name not like Action
method. So in this kind of scenario our default route won’t work significantly.
To fetch the incoming value from the browser when the parameter is getting passed,
MVC framework provides a simple way to address this problem. It is by using the parameter
inside the Action method.
Step 2
Change the EmployeeController class using the following code.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller {
// GET: Employee
public ActionResult Search(string name){
var input = Server.HtmlEncode(name);
return Content(input);
}
}
}
If you add a parameter to an action method, then the MVC framework will look for the
value that matches the parameter name. It will apply all the possible combination to find out the
parameter value. It will search in the Route data, query string, etc.
Hence, if you request for /Employee/Mark”, then the MVC framework will decide that I
need a parameter with “UserInput”, and then Mark will get picked from the URL and that will
get automatically passed.
Server.HtmlEncode will simply convert any kind of malicious script in plain text. When
the above code is compiled and executed and requests the following URL
http://localhost:61465/Employee/Mark, you will get the following output.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
As you can see in the above screenshot, Mark is picked from the URL.
12.7. ASP.NET MVC – Action Methods:
ASP.NET MVC Action Methods are responsible to execute requests and generate
responses to it. By default, it generates a response in the form of ActionResult. Actions typically
have a one-to-one mapping with user interactions.
For example, enter a URL into the browser, click on any particular link, and submit a
form, etc. Each of these user interactions causes a request to be sent to the server. In each case,
the URL of the request includes information that the MVC framework uses to invoke an action
method. The one restriction on action method is that they have to be instance method, so they
cannot be static methods. Also there is no return value restrictions. So you can return the string,
integer, etc.
12.7.1. Request Processing:
Actions are the ultimate request destination in an MVC application and it uses the
controller base class. Let's take a look at the request processing.
When a URL arrives, like /Home/index, it is the UrlRoutingModule that inspects and
understands that something configured within the routing table knows how to handle
that URL.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
The UrlRoutingModule puts together the information we've configured in the routing
table and hands over control to the MVC route handler.
The MVC route handler passes the controller over to the MvcHandler which is an
HTTP handler.
MvcHandler uses a controller factory to instantiate the controller and it knows what
controller to instantiate because it looks in the RouteData for that controller value.
Once the MvcHandler has a controller, the only thing that MvcHandler knows about
is IController Interface, so it simply tells the controller to execute.
When it tells the controller to execute, that's been derived from the MVC's controller
base class. The Execute method creates an action invoker and tells that action invoker
to go and find a method to invoke, find an action to invoke.
The action invoker, again, looks in the RouteData and finds that action parameter
that's been passed along from the routing engine.
12.7.2. Types of Action:
Actions basically return different types of action results. The ActionResult class is the
base for all action results. Following is the list of different kind of action results and its behavior.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Let’s have a look at a simple example from the previous chapter in which we have
created an EmployeeController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 2
Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 3
Set the name to CustomerController and click ‘Add’ button.
Now you will see a new C# file ‘CustomerController.cs’ in the Controllers folder, which
is open for editing in Visual Studio as well.
Similarly, add one more controller with name HomeController. Following is the
HomeController.cs class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is Home Controller";
}
}
}
Step 4
Run this application and you will receive the following output.
Step 5
Add the following code in Customer controller, which we have created above.
public string GetAllCustomers(){
return @"<ul>
<li>Ali Raza</li>
<li>Mark Upston</li>
<li>Allan Bommer</li>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<li>Greg Jerry</li>
</ul>";
}
Step 6
Run this application and request
for http://localhost:61465/Customer/GetAllCustomers. You will see the following output.
You can also redirect to actions for the same controller or even for a different controller.
Following is a simple example in which we will redirect from HomeController to
Customer Controller by changing the code in HomeController using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers{
public class HomeController : Controller{
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
// GET: Home
public ActionResult Index(){
return RedirectToAction("GetAllCustomers","Customer");
}
}
}
As you can see, we have used the RedirectToAction() method ActionResult, which takes
two parameters, action name and controller name.
When you run this application, you will see the default route will redirect it to
/Customer/GetAllCustomers
An action filter is an attribute that you can apply to a controller action or an entire
controller that modifies the way in which the action is executed. The ASP.NET MVC framework
includes several action filters −
Filters are executed in the order listed above. For example, authorization filters are
always executed before action filters and exception filters are always executed after every other
type of filter.
Authorization filters are used to implement authentication and authorization for controller
actions. For example, the Authorize filter is an example of an Authorization filter.
Let’s take a look at a simple example by creating a new ASP.Net MVC project.
Step 1
Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 2
From the left pane, select Templates → Visual C# → Web.
Step 3
In the middle pane, select ASP.NET Web Application.
Step 4
Enter project name MVCFiltersDemo in the Name field and click ok to continue and you
will see the following dialog which asks you to set the initial content for the ASP.NET project.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 5
To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add
folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
Step 6
To add a controller, right-click on the controller folder in the solution explorer and select
Add → Controller.
It will display the Add Scaffold dialog.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 7
Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8
Set the name to HomeController and click ‘Add’ button.
You will see a new C# file ‘HomeController.cs’ in the Controllers folder, which is open
for editing in Visual Studio as well.
12.8.3. Apply Action Filter:
An action filter can be applied to either an individual controller action or an entire
controller. For example, an action filter OutputCache is applied to an action named Index() that
returns the string. This filter causes the value returned by the action to be cached for 15 seconds.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
To make this a working example, let’s modify the controller class by changing the action
method called Index using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 15)]
Let’s add another action method, which will display the current time.
namespace MVCFiltersDemo.Controllers{
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 15)]
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[OutputCache(Duration = 20)]
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Request for the following URL, http://localhost:62833/Home/GetCurrentTime, and
you will receive the following output.
If you refresh the browser, you will see the same time because the action is cached for 20
seconds. It will be updated when you refresh it after 20 seconds.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
namespace MVCFiltersDemo.ActionFilters {
public class MyLogActionFilter : ActionFilterAttribute{
public override void OnActionExecuting(ActionExecutingContext filterContext){
Log("OnActionExecuting", filterContext.RouteData);
}
using System.Web;
using System.Web.Mvc;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
namespace MVCFiltersDemo.Controllers {
[MyLogActionFilter]
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 10)]
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[OutputCache(Duration = 10)]
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Run the application and then observe the output window.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
As seen in the above screenshot, the stages of processing the action are logged to the
Visual Studio output window.
12.9. ASP.NET MVC – Action Selectors:
Action selectors are attributes that can be applied to action methods and are used to
influence which action method gets invoked in response to a request. It helps the routing engine
to select the correct action method to handle a particular request.
It plays a very crucial role when you are writing your action methods. These selectors
will decide the behavior of the method invocation based on the modified name given in front of
the action method. It is usually used to alias the name of the action method.
There are three types of action selector attributes –
ActionName
NonAction
ActionVerbs
12.9.1. ActionName:
This class represents an attribute that is used for the name of an action. It also allows
developers to use a different action name than the method name.
Let’s take a look at a simple example from the last chapter in which we have
HomeController containing two action methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
}
}
Let’s apply the the ActionName selector for GetCurrentTime by writing
[ActionName("CurrentTime")] above the GetCurrentTime() as shown in the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
return "This is ASP.Net MVC Filters Tutorial";
}
[ActionName("CurrentTime")]
public string GetCurrentTime(){
return DateTime.Now.ToString("T");
}
}
}
Now run this application and enter the following URL in the
browser http://localhost:62833/Home/CurrentTime, you will receive the following output.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
You can see that we have used the CurrentTime instead of the original action name,
which is GetCurrentTime in the above URL.
12.9.2. NonAction:
NonAction is another built-in attribute, which indicates that a public method of a
Controller is not an action method. It is used when you want that a method shouldn’t be treated
as an action method.
Let’s take a look at a simple example by adding another method in HomeController and
also apply the NonAction attribute using the following code.
using MVCFiltersDemo.ActionFilters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public string Index(){
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
[ActionName("CurrentTime")]
public string GetCurrentTime(){
return TimeString();
}
[NonAction]
public string TimeString(){
return "Time is " + DateTime.Now.ToString("T");
}
}
}
The new method TimeString is called from the GetCurrentTime() but you can’t use it as
action in URL.
Let’s run this application and specify the following
URL http://localhost:62833/Home/CurrentTime in the browser. You will receive the
following output.
Let us now check the /TimeString as action in the URL and see what happens.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
HttpGet
HttpPost
HttpPut
HttpDelete
HttpOptions
HttpPatch
using System.Web;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
public ActionResult Search(string name = “No name Entered”){
var input = Server.HtmlEncode(name);
return Content(input);
}
}
}
Now let’s add another action method with the same name using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
//public ActionResult Index()
//{
// return View();
//}
}
When you run this application, it will give an error because the MVC framework is
unable to figure out which action method should be picked up for the request.
Let us specify the HttpGet ActionVerb with the action you want as response using the
following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller{
// GET: Employee
//public ActionResult Index()
//{
// return View();
//}
[HttpGet]
public ActionResult Search(){
var input = "Another Search action";
return Content(input);
}
}
}
When you run this application, you will receive the following output.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 2
From the left pane, select Templates → Visual C# → Web.
Step 3
In the middle pane, select ASP.NET Web Application.
Step 4
Enter the project name ‘MVCViewDemo’ in the Name field and click Ok to continue.
You will see the following dialog which asks you to set the initial content for the ASP.NET
project.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 5
To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add
folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content. We now need to add
controller.
Step 6
Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 7
Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8
Set the name to HomeController and click ‘Add’ button.
You will see a new C# file ‘HomeController.cs’ in the Controllers folder which is open
for editing in Visual Studio as well.
Let’s update the HomeController.cs file, which contains two action methods as shown in
the following code.
using System;
using System.Collections.Generic;
using System.Linq;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System.Web;
using System.Web.Mvc;
namespace MVCViewDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return View();
}
As MyController action simply returns the string, to return a View from the action we
need to add a View first.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 10
Before adding a view let’s add another action, which will return a default view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCViewDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return View();
}
You can see here that we have an error and this error is actually quite descriptive, which
tells us it can't find the MyView view.
Step 12
To add a view, right-click inside the MyView action and select Add view.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
It will display the Add View dialog and it is going to add the default name.
Step 13
Uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button.
We now have the default code inside view.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 14
Add some text in this view using the following code.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>MyView</title>
</head>
<body>
<div>
Hi, I am a view
</div>
</body>
</html>
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 15
Run this application and apend /Home/MyView to the URL in the browser. Press enter
and you will receive the following output.
Step 2
From the left pane, select Templates → Visual C# → Web.
Step 3
In the middle pane, select ASP.NET Web Application.
Step 4
Enter the project name ‘MVCSimpleApp’ in the Name field and click Ok to continue.
You will see the following dialog which asks you to set the initial content for the ASP.NET
project.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 5
To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add
folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
We need to add a controller now.
Step 6
Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 7
Select the MVC 5 Controller – with read/write actions option. This template will create
an Index method with default action for Controller. This will also list other methods like
Edit/Delete/Create as well.
Step 8
Click ‘Add’ button and Add Controller dialog will appear.
Step 9
Set the name to EmployeeController and click the ‘Add’ button.
Step 10
You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is
open for editing in Visual Studio with some default actions.
using System;
using System.Collections.Generic;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCSimpleApp.Controllers {
public class EmployeeController : Controller{
// GET: Employee
public ActionResult Index(){
return View();
}
// GET: Employee/Details/5
public ActionResult Details(int id){
return View();
}
// GET: Employee/Create
public ActionResult Create(){
return View();
}
// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
try{
// TODO: Add insert logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
// GET: Employee/Edit/5
public ActionResult Edit(int id){
return View();
}
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
// POST: Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
try{
// TODO: Add update logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
// GET: Employee/Delete/5
public ActionResult Delete(int id){
return View();
}
// POST: Employee/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection){
try{
// TODO: Add delete logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
}
}
Let’s add a model.
Step 11
Right-click on the Models folder in the solution explorer and select Add → Class.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 12
Select Class in the middle pan and enter Employee.cs in the name field.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Step 13
Add some properties to Employee class using the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCSimpleApp.Models {
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
Let’s update the EmployeeController.cs file by adding one more method, which will
return the list of employee.
[NonAction]
public List<Employee> GetEmployeeList(){
return new List<Employee>{
new Employee{
ID = 1,
Name = "Allan",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new Employee{
ID = 2,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new Employee{
ID = 3,
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new Employee{
ID = 4,
Name = "Laura",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
}
Step 14
Update the index action method as shown in the following code.
public ActionResult Index(){
var employees = from e in GetEmployeeList()
orderby e.ID
select e;
return View(employees);
}
Step 15
Run this application and append /employee to the URL in the browser and press Enter.
You will see the following output.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
As seen in the above screenshot, there is an error and this error is actually quite
descriptive which tells us it can't find the Index view.
Step 16
Hence to add a view, right-click inside the Index action and select Add view.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
It will display the Add View dialog and it is going to add the default name.
Step 17
Select the List from the Template dropdown and Employee in Model class dropdown and
also uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button.
It will add some default code for you in this view.
@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Index</title>
</head>
<body>
<p>@Html.ActionLink("Create New", "Create")</p>
<table class = "table">
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.JoiningDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
<td>
@Html.DisplayFor(modelItem => item.JoiningDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
</table>
</body>
</html>
Step 18
Run this application and you will receive the following output.
.NET is a software framework which is designed and developed by Microsoft. The first
version of .Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual
machine for compiling and executing programs written in different languages like C#, VB.Net
etc.It is used to develop Form-based applications, Web-based applications, and Web services.
There is a variety of programming languages available on the .Net platform, VB.Net
and C# being the most common ones. It is used to build applications for Windows, phone, web
etc. It provides a lot of functionalities and also supports industry standards.
.NET Framework supports more than 60 programming languages in which 11
programming languages are designed and developed by Microsoft. The remaining Non-
Microsoft Languages which are supported by .NET Framework but not designed and developed
by Microsoft.
11 Programming Languages which are designed and developed by Microsoft are –
C#.NET
VB.NET
C++.NET
J#.NET
F#.NET
JSCRIPT.NET
WINDOWS POWERSHELL
IRON RUBY
IRON PYTHON
C OMEGA
ASML(Abstract State Machine Language)
Visual Studio is the development tool which is used to design and develop the .NET
applications. For using Visual Studio, the user has to first install the .NET framework
on the system.
In the older version of Windows OS like XP SP1, SP2 or SP3, .NET framework was
integrated with the installation media.
Windows 8, 8.1 or 10 do not provide a pre-installed version 3.5 or later
of .NETFramework. Therefore, a version higher than 3.5 must be installed either from a
Windows installation media or from the Internet on demand. Windows update will give
recommendations to install the .NET framework.
13.6. C#.net Introduction:
C# is a modern, general-purpose, object-oriented programming language developed by
Microsoft and approved by European Computer Manufacturers Association (ECMA) and
International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Visual C# Express and Visual Web Developer Express edition are trimmed down
versions of Visual Studio and has the same appearance. They retain most features of Visual
Studio. In this tutorial, we have used Visual C# 2010 Express.
13.11. Writing C# Programs on Linux or Mac OS:
Although the.NET Framework runs on the Windows operating system, there are some
alternative versions that work on other operating systems. Mono is an open-source version of the
.NET Framework which includes a C# compiler and runs on several operating systems, including
various flavors of Linux and Mac OS.
The stated purpose of Mono is not only to be able to run Microsoft .NET applications
cross-platform, but also to bring better development tools for Linux developers. Mono can be run
on many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris, and
UNIX.
13.12. C# - Program Structure:
Before we study basic building blocks of the C# programming language, let us look at a
bare minimum C# program structure so that we can take it as a reference in upcoming lectures.
13.13. Creating Hello World Program:
A C# program consists of the following parts −
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" –
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
}
When this code is compiled and executed, it produces the following result −
Hello World
Let us look at the various parts of the given program –
The first line of the program using System; - the using keyword is used to include the
System namespace in the program. A program generally has multiple using
statements.
The next line has the namespace declaration. A namespace is a collection of classes.
The HelloWorldApplication namespace contains the class HelloWorld.
The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple
methods. Methods define the behavior of the class. However, the HelloWorld class
has only one method Main.
The next line defines the Main method, which is the entry point for all C# programs.
The Main method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add comments in the
program.
The Main method specifies its behavior with the statement Console.WriteLine("Hello
World");
WriteLine is a method of the Console class defined in the System namespace. This
statement causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey(); is for the VS.NET Users. This makes the program
wait for a key press and it prevents the screen from running and closing quickly when
the program is launched from Visual Studio .NET.
It is worth to note the following points −
C# is case sensitive.
All statements and expression must end with a semicolon (;).
The program execution starts at the Main method.
Unlike Java, program file name could be different from the class name.
13.14. Compiling and Executing the Program:
If you are using Visual Studio.Net for compiling and executing C# programs, take the
following steps −
namespace RectangleApplication {
class Rectangle {
// member variables
double length;
double width;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Comments are used for explaining code. Compilers ignore the comment entries. The
multiline comments in C# programs start with /* and terminates with the characters */ as shown
below −
/* This program demonstrates
The basic syntax of C# programming
Language */
Single-line comments are indicated by the '//' symbol. For example,
}//end class Rectangle
13.15.4. Member Variables:
Variables are attributes or data members of a class, used for storing data. In the preceding
program, the Rectangle class has two member variables named length and width.
13.15.5. Member Functions:
Functions are set of statements that perform a specific task. The member functions of a
class are declared within the class. Our sample class Rectangle contains three member
functions: AcceptDetails, GetArea and Display.
13.15.6. Instantiating a Class:
In the preceding program, the class ExecuteRectangle contains the Main()method and
instantiates the Rectangle class.
13.15.7. Identifiers:
An identifier is a name used to identify a class, variable, function, or any other user-
defined item. The basic rules for naming classes in C# are as follows –
A name must begin with a letter that could be followed by a sequence of letters, digits
(0 - 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] {
} . ; : " ' / and \. However, an underscore ( _ ) can be used.
It should not be a C# keyword.
13.15.8. C# Keywords:
Keywords are reserved words predefined to the C# compiler. These keywords cannot be
used as identifiers. However, if you want to use these keywords as identifiers, you may prefix the
keyword with the @ character.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
In C#, some identifiers have special meaning in context of code, such as get and set are
called contextual keywords.
The following table lists the reserved keywords and contextual keywords in C# −
Reserved Keywords
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
in (generic
foreach goto if implicit in int
modifier)
interface internal is lock long namespace new
out (generic
null object operator out override params
modifier)
private protected public readonly ref return sbyte
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile while
Contextual Keywords
add alias ascending descending dynamic from get
global group into join let orderby partial (type)
partial
remove select set
(method)
Value types
Reference types
Pointer types
To get the exact size of a type or a variable on a particular platform, you can use the
sizeof method. The expression sizeof (type) yields the storage size of the object or type in bytes.
Following is an example to get the size of int type on any machine –
using System;
namespace DataTypeApplication {
class Program {
static void Main(string[] args) {
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Size of int: 4
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Type Example
Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point types float and double
Decimal types decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types
C# also allows defining other value types of variable such as enum and reference types of
variables such as class.
13.17.1. Defining Variables:
Syntax for variable definition in C# is −
<data_type><variable_list>;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Here, data_type must be a valid C# data type including char, int, float, double, or any
user-defined data type, and variable_list may consist of one or more identifier names separated
by commas.
Some valid variable definitions are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a variable at the time of definition as −
int i = 100;
13.17.2. Initializing Variables:
Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is −
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign
followed by a constant expression as −
<data_type><variable_name> = value;
Some examples are −
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes
program may produce unexpected result.
The following example uses various types of variables –
using System;
namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
13.17.3. Accepting Values from User:
The Console class in the System namespace provides a function ReadLine() for accepting
input from the user and store it into a variable.
For example,
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type,
because Console.ReadLine() accepts the data in string format.
13.17.4. Lvalue and Rvalue Expressions in C#:
There are two kinds of expressions in C# −
lvalue − An expression that is an lvalue may appear as either the left-hand or right-
hand side of an assignment.
rvalue − An expression that is an rvalue may appear on the right- but not left-hand
side of an assignment.
Variables are lvalues and hence they may appear on the left-hand side of an assignment.
Numeric literals are rvalues and hence they may not be assigned and can not appear on the left-
hand side. Following is a valid C# statement −
int g = 20;
But following is not a valid statement and would generate compile-time error −
10 = 20;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
switch statement
4 A switch statement allows a variable to be tested for equality against a list of
values.
nested switch statements
5
You can use one switch statement inside another switchstatement(s).
14.1.1. C# - if Statement:
An if statement consists of a boolean expression followed by one or more statements.
Syntax
The syntax of an if statement in C# is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the boolean expression evaluates to true, then the block of code inside the if statement
is executed. If boolean expression evaluates to false, then the first set of code after the end of the
if statement(after the closing curly brace) is executed.
Flow Diagram
Example
using System;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
Example
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 100;
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100
14.1.3. The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if, else if, else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C# is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
Example
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 100;
Example
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
//* local variable definition */
int a = 100;
int b = 200;
switch(expression) {
case constant-expression1 :
statement(s);
break;
case constant-expression2 :
case constant-expression3 :
statement(s);
break;
The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral
or enumerated type.
You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, then it will raise a
compile time error.
A switch statement can have an optional default case, which must appear at the end
of the switch. The default case can be used for performing a task when none of the
cases is true.
Flow Diagram
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
char grade = 'B';
switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
14.1.6. C# - nested switch Statements:
It is possible to have a switch as part of the statement sequence of an outer switch. Even
if the case constants of the inner and outer switch contain common values, no conflicts will arise.
Syntax
The syntax for a nested switch statement is as follows −
switch(ch1) {
case 'A':
Console.WriteLine("This A is part of outer switch" );
switch(ch2) {
case 'A':
Console.WriteLine("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
}
Example
using System;
namespace DecisionMaking {
class Program {
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
switch (a) {
case 100:
Console.WriteLine("This is part of outer switch ");
switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
14.1.7. The ? : Operator:
We have covered conditional operator ? : in previous chapter which can be used to
replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is
evaluated and its value becomes the value of the expression.
14.2. C# - Loops:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
There may be a situation, when you need to execute a block of code several number of
times. In general, the statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or a group of statements multiple times
and following is the general from of a loop statement in most of the programming languages –
Syntax
The syntax of a while loop in C# is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body is skipped and the first statement after the while
loop is executed.
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
a++;
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
14.2.2. C# - For Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
The syntax of a for loop in C# is −
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop –
The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again testing for a
condition). After the condition becomes false, the for loop terminates.
Flow Diagram
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
Console.WriteLine("value of a: {0}", a);
a = a + 1;
}
while (a < 20);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
14.2.4. C# - Nested Loops:
C# allows to use one loop inside another loop. Following section shows few examples to
illustrate the concept.
Syntax
The syntax for a nested for loop statement in C# is as follows −
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C# is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C# is as follows −
do {
statement(s);
do {
statement(s);
}
while( condition );
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
}
while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type
of loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 –
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int i, j;
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
14.2.5. Loop Control Statements:
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
C# provides the following control statements.
When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will
stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
if (a > 15) {
/* terminate the loop using break statement */
break;
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
}
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
14.2.5.2. C# - Continue Statement:
The continue statement in C# works somewhat like the break statement. Instead of
forcing termination, however, continue forces the next iteration of the loop to take place,
skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of
the loop to execute. For the while and do...while loops, continue statement causes the program
control passes to the conditional tests.
Syntax
The syntax for a continue statement in C# is as follows −
continue;
Flow Diagram
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
while (a < 20);
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
14.2.6. Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the for loop are
required, you can make an endless loop by leaving the conditional expression empty.
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
for (; ; ) {
Console.WriteLine("Hey! I am Trapped");
}
}
}
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but programmers more commonly use the for(;;)
construct to signify an infinite loop.
14.3. C# - Methods:
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C
A method is a group of statements that together perform a task. Every C# program has at
least one class with a method named Main.
To use a method, you need to −
int result;
return result;
}
...
}
14.3.2. Calling Methods in C#:
You can call a method using the name of the method. The following example illustrates
this –
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
return result;
}
}
class Test {
static void Main(string[] args) {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
namespace CalculatorApplication {
class NumberManipulator {
public int factorial(int num) {
/* local variable declaration */
int result;
if (num == 1) {
return 1;
} else {
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
//calling the factorial method {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Online Courseware for B.TechComputer Science and Engineering Program(Autonomy)
Paper Name: Web Technology
Paper Code: CS702C