WT&WS
WT&WS
(R20A1203)
DIGITAL NOTES
B.TECH III YEAR–I SEM
(2023-2024)
PREPARED BY
A.VIJETHA
K.SHANTHI
I.UMA MAHESHWARA RAO
1
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
B.TECH - III- YEAR I-SEM-IT L/T/P/C
3/-/-/3
1. To study the insights of the Web architecture and how servlets works.
2. To gain knowledge in interfacing Java Servlet Program with JDBC Connection
3. To be trained to dynamically generate the web pages using Java Server Pages.
4. To understand the designing applications over web using Spring Framework.
5. To get acquainted with applications over the web using ‘Django’ Framework.
UNIT-I:
Web Basics and Overview: Introduction to Internet, World Wide Web, Web Browsers, URL , HTTP.
PHP: Declaring Variables, Data types, Operators, Control structures, Functions. MVC Framework and
Design Pattern, Types of PHP MVC framework.
UNIT-II
Servlets: Introduction to Servlets, Benefits of Servlets, use as controller in MVC, servlet lifecycle,
basic HTTP, Reading Servlet parameters servlet session, cookies , Servlets API.
JDBC:JDBC Architecture,JDBC API,Connecting to a Database Using JDBC.
UNIT-III
Java Server Pages: Generating Dynamic Content, Using Scripting Elements, Implicit JSP Objects.
Conditional Processing – Displaying Values, setting attributes, Error Handling and Debugging.
UNIT-IV
Java Script: Introduction to Java Script, Declaring variables, Functions, Event handlers (onclick, on
submit, etc.,) and Form Validation.
Spring Framework: Overview, Controllers, Handler Methods, and Developing Web Application
using spring.
UNIT-V
Django: Introduction to Django, Django architecture, Django Models and Database Backends,
Developing Web Application using Django.
TEXT BOOKS:
2
1. Hans Bergsten , Java Server Pages, O’Reilly, 2003
2. Jason Hunter, William Crawford , Java Servlet Programming, Second Edition, , O'Reilly Media
REFERENCE BOOKS:
1. Joseph J. Bambara, Paul R. Allen, Mark Ashnault, Ziyad Dean, Thomas Garben, Sherry Smith J2EE
UNLEASHED –– SAMS Techmedia 5 StepahnieBodoff, Dale Green, Kim Hasse, Eric Jendrock,
Monica Pawlan, Beth Stearns , The J2EE Tutorial, Pearson Education , Asia.
2. Learning Django Web Development, SanjeevJaiswalRatanKumar,PACKT Publishing.
3. https://www.djangoproject.com/ spring framework (IBM).
Course Outcomes:
1. Analyze a web page and identify its elements and attributes of PHP Frame Work.
2. Installation and usage of Server Software‘s & Web.xml Deployment.
3. Database Connectivity to web applications.
4. Build web applications using Servlet and JSP.
5.Build web applications using to Django.
3
INDEX
4
functions 85-86
Event handlers 86-89
5
UNIT - I
Web Basics and Overview: Introduction to Internet, World Wide Web, Web Browsers, URL, HTTP.
PHP: Declaring Variables, Data types, Operators, Control structures, Functions, MVC Framework and
Design Pattern, Types of PHP MVC framework.
Introduction to Internet:
The Internet is the global system of interconnected computer networks that use the Internet
protocol suite (TCP/IP) to link devices worldwide. It is a network of networks that consists of
private, public, academic, business, and government networks of local to global scope, linked by
a broad array of electronic, wireless, and optical networking technologies. The Internet carries a
vast range of information resources and services.
History of Internet:
This marvelous tool has quite a history that holds its roots in the cold war scenario. A
need was realized to connect the top universities of the United States so that they can share all
the research data without having too much of a time lag. This attempt was a result of Advanced
Research Projects Agency (ARPA) which was formed at the end of 1950s just after the Russians
had climbed the space era with the launch of Sputnik. After the ARPA got success in 1969, it
didn’t take the experts long to understand that how much potential can this interconnection tool
have. In 1971 Ray Tomlinson made a system to send electronic mail. This was a big step in the
making as this opened gateways for remote computer accessing i.e. telnet.
During all this time, rigorous paper work was being done in all the elite research
institutions. From giving every computer an address to setting out the rules, everything was
getting penned down. 1973 saw the preparations for the vital TCP/IP and Ethernet services. At
6
the end of 1970s, Usenet groups had surfaced up. By the time the 80s had started, IBM came up
with its PC based on Intel 8088 processor which was widely used by students and universities for
it solved the purpose of easy computing. By 1982, the Defense Agencies made the TCP/IP
compulsory and the term internet was coined. The domain name services arrived in the year
1984 which is also the time around which various internet based marked their debut. A worm, or
a rust the computers, attacked in 1988 and disabled over 10% of the computer systems all over
the world. While most of the researchers regarded it as an opportunity to enhance computing as it
was still in its juvenile phase, quite a number of computer companies became interested in
dissecting the cores of the malware which resulted to the formation Computer Emergency
Rescue Team (CERT). Soon after the world got over with the computer worm, World Wide Web
came into existence.
Embedded hyperlinks permit users to navigate between web pages. Multiple web pages
with a common theme, a common domain name, or both, make up a website. Website content
can largely be provided by the publisher, or interactively where users contribute content or the
content depends upon the users or their actions. Websites may be mostly informative, primarily
7
for entertainment, or largely for commercial, governmental, or non-governmental organizational
purposes.
8
WWW is another example of client/server computing. Each time a link is followed, the client is
requesting a document (or graphic or sound file) from a server (also called a Web server) that's
part of the World Wide Web that "serves" up the document. The server uses a protocol called
HTTP or Hyper Text Transport Protocol. The standard for creating hypertext documents for the
WWW is Hyper Text Markup Language or HTML. HTML essentially codes plain text
documents so they can be viewed on the Web.
Web Browsers:
WWW Clients, or "Browser": The program you use to access the WWW is known as a
browser because it "browses" the WWW and requests these hypertext documents. Browsers can
be graphical, allows seeing and hearing the graphics and audio.
Text-only browsers (i.e., those with no sound or graphics capability) are also available. All of
these programs understand http and other Internet protocols such as FTP, gopher, mail, and
news, making the WWW a kind of "one stop shopping" for Internet users.
9
Year List of Web browsers
1991 World Wide Web (Nexus)
IBM WebExplorer, Netscape Navigator, SlipKnot 1.0, MacWeb, IBrowse, Agora (Argo),Minuet
1994
Arachne 1.0, Internet Explorer 3.0, Netscape Navigator 3.0, Opera 2.0,
1996
PowerBrowser 1.5,[4] Cyberdog, Amaya 0.9,[5] AWeb, Voyager
Internet Explorer 4.0, Netscape Navigator 4.0, Netscape Communicator 4.0, Opera
1997
3.0,[6] Amaya 1.0[5]
2000 Konqueror, Netscape 6, Opera 4,[7] Opera 5,[8] K-Meleon 0.2, Amaya 3.0,[5] Amaya 4.0[5]
2002 Netscape 7, Mozilla 1.0, Phoenix 0.1, Links 2.0, Amaya 6.0,[5] Amaya 7.0[5]
2003 Opera 7,[10] Apple Safari 1.0, Epiphany 1.0, Amaya 8.0[5]
Opera 8,[11] Apple Safari 2.0, Netscape Browser 8.0, Epiphany 1.8, Amaya 9.0,[5] AOL
2005
Explorer 1.0, Maxthon 1.0,Shiira 1.0
Mozilla Firefox 2.0, Internet Explorer 7, Opera 9,[12], SeaMonkey 1.0, K-Meleon 1.0,
2006
Galeon 2.0, Camino 1.0, Avant11, iCab 3
2007 Apple Safari 3.0, Maxthon 2.0, Netscape Navigator 9, NetSurf 1.0, Flock 1.0, Conkeror
Google Chrome 1, Mozilla Firefox 3, Opera 9.5,[13], Apple Safari 3.1, Konqueror 4, Amaya 10.0,[5]
2008
Flock 2, Amaya 11.0[5]
Google Chrome 2–3, Mozilla Firefox 3.5, Internet Explorer 8, Opera 10,[14], Apple Safari 4,
2009
SeaMonkey 2, Camino 2,surf, Pale Moon 3.0[15]
Google Chrome 4–8, Mozilla Firefox 3.6, Opera 10.50,[16], Opera 11, Apple Safari 5, K-
2010 Meleon 1.5.4,
Google Chrome 9–16, Mozilla Firefox 4-9, Internet Explorer 9, Opera 11.50, Apple
2011
Safari 5.1, Maxthon 3.0, SeaMonkey 2.1–2.6
10
Google Chrome 17–23, Mozilla Firefox 10–17, Internet Explorer 10, Opera 12, Apple
2012
Safari 6, Maxthon 4.0, SeaMonkey 2.7-2.14
2013 Google Chrome 24–31, Mozilla Firefox 18–26, Internet Explorer 11, Opera 15–18, Apple
11
Safari 7, SeaMonkey 2.15-2.23
2014 Google Chrome 32–39, Mozilla Firefox 27–34, Opera 19–26, Apple Safari 8
2015 Google Chrome 40–47, Microsoft Edge, Mozilla Firefox 35–43, Opera 27–34, Vivaldi
Google Chrome 48–55, Mozilla Firefox 44–50, Microsoft Edge 14, Opera 35–42, Apple
2016
Safari 10, SeaMonkey 2.24–2.30, Pale Moon 26.0.0[17], Pale Moon 27.0.0[18]
Google Chrome 56–60, Microsoft Edge 15, Mozilla Firefox 51–55.0.2, Opera 43–45, OperaNeon
2017
Domains divide World Wide Web sites into categories based on the nature of their owner, and
they form part of a site's address, or uniform resource locator (URL). Common top-level
domains are:
12
.edu—educational site (universities, .info—commercial and personal
schools, etc.)
Additional three-letter, four-letter, and longer top-level domains are frequently added.
Each country linked to the Web has a two-letter top-level domain, for example .fr is France, .ie is
Ireland.
For example, when you enter a URL in your browser, this actually sends an HTTP command to
the Web server directing it to fetch and transmit the requested Web page. The other main
standard that controls how the World Wide Web works is HTML, which covers how Web pages
are formatted and displayed.
HTTP is called a stateless protocol because each command is executed independently, without
any knowledge of the commands that came before it. This is the main reason that it is difficult to
implement Web sites that react intelligently to user input.
HTTPS:
A similar abbreviation, HTTPS means Hyper Text Transfer Protocol Secure. Basically, it is the
secure version of HTTP. Communications between the browser and website are encrypted by
Transport Layer Security (TLS), or its predecessor, Secure Sockets Layer (SSL).
PHP:
INTRODUCTION:
13
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. RasmusLerdorf unleashed the first version of PHP way back in 1994.
PHP is a server side scripting language that is embedded in HTML. PHP scripts are executed
on the server
It is used to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, Microsoft SQL Server , etc.)
PHP is an open source software.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the
Unix side. The MySQL server, once started, executes even very complex queries with huge
result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP Syntax is C-Like.
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.
The other uses of PHP are:
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send
data, return data to the user.
You add, delete, and modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP:
Efficiency
Security
14
Flexibility
Familiarity
All PHP code must be included inside one of the three special markup tags are recognized by the
PHP Parser.Simplicity
<script language="PHP">...</script>
DECLARING VARIABLE:
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.
A variable is used to store information.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables used before they are assigned have default values.
PHP does a good job of automatically converting types from one to another whennecessary.
15
PHP variables are Perl-like.
Syntax: $var_name = value;
Eg: creating a variable containing a string, and a variable containing a number:
<?php
$txt="HelloWorld!";
$x=16;
?>
16
Naming Rules for Variables:
A variable name must start with a letter or an underscore "_"
A variable name can only contain alpha-numeric characters and underscores (a-z, A-
Z, 0-9, and _ )
A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with an underscore ($my_string), or with capitalization/Camel notation
($myString)
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Example
17
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest(); // using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
Example
<?php
$x = 5; $y = 10;
function myTest() {
global $x, $y;
$y = $x + $y; }
myTest();
echo $y; //
?>
outputs 15
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to update
global variables directly. The example above can be rewritten like this:
Example
<?php
$x = 5;
18
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
19
PHP The static Keyword
Normally, when a function is completed / executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x=$x+5;
}
myTest();
myTest();
myTest();
?>
Output: 5 10 15
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
Note: The variable is still local to the function.
Variable Naming
Rules for naming a variable is-
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores but you cannot use characters like
+ , - , % , ( , ) . & , etc
There is no size limit for variables.
Data Types:
PHP has a total of eight data types which we use to construct our variables:
20
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer-defined classes. Compound types
NULL: is a special type that only has one value: NULL.
Resources: are special variables that hold references to resources external Special types
to PHP (such as database connections)
21
The first four are simple types, and the next two (arrays and objects) are compound - the compound
types can package up other arbitrary values of arbitrary type, whereas the simpletypes cannot.
Integers:
Integers are primitive data types. They are whole numbers, without a decimal point, like 4195.
They are the simplest type. They correspond to simple whole numbers, both positive and negative
{..., -2, -1, 0, 1, 2, ...}.
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading
0x.
Ex: $v = 12345;
$var1 = -12345 + 12345;
notation.php
<?php
$var1 = 31; $var2 = 031; $var3 = 0x31;
Output:
31
25
49
echo "$var1\n$var2\n$var3"; ?>
The default notation is the decimal. The script shows these three numbers in decimal. In Java and
C, if an integer value is bigger than the maximum value allowed, integer overflow happens. PHP
works differently. In PHP, the integer becomes a float number. Floating point numbers have greater
boundaries.In 32bit system, an integer value size is four bytes. The maximum integer value is
2147483647.
boundary.php
<?php
$var = PHP_INT_MAX;
echovar_dump($var);
$var++;
echovar_dump($var);
?>
We assign a maximum integer value to the $var variable. We increase the variable by one. And
we compare the contents.
22
Output:
int(2147483647)
float(2147483648)
As we have mentioned previously, internally, the number becomes a floating point value.
var_dump():The PHP var_dump() function returns the data type and value.
Doubles or Floating point numbers:
Floating point numbers represent real numbers in computing. Real numbers measure continuous
quantities like weight, height or speed. Floating point numbers in PHP can be larger than integers
and they can have a decimal point. The size of a float is platform dependent.
<?php
$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;
var_dump($a);var_dump($b); var_dump($c);var_dump($d);
?>
Boolean:
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing.
<?php
$male = False;
$r = rand(0, 1);
$male = $r ? True: False;
if ($male) {
23
echo "We will use name John\n";
} else {
We can use single quotes and double quotes to create string literals.
The script outputs two strings to the console. The \n is a special sequence, a new line.
24
?>
O/P: Hello Kalpana! What a nice day!
FALSE. The example below searches for the text "world" in the string "Hello world!":
Example:
<?php
echo strpos("Hello world!", "world");
?>
output: 6
Tip: The first character position in a string is 0 (not 1).
Replace Text within a String:
The PHP str_replace() function replaces some characters with some other characters in a string. The
example below replaces the text "world" with "Dolly":
Array:
Array is a complex data type which handles a collection of elements. Each of the elements can be
accessed by an index. An array stores multiple values in one single variable. In the following
25
example $cars is an array. The PHP var_dump() function returns the data type and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
print_r($cars);
var_dump($cars);
?>
The array keyword is used to create a collection of elements. In our case we have names. The
print_r function prints human readable information about a variable to the console.
O/P: Array ( [0] => Volvo [1] => BMW [2] => Toyota )
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
An object is a data type which stores data and information on how to process that data. In PHP, an
object must be explicitly declared. First we must declare a class of object. For this, we use the class
keyword. A class is a structure that can contain properties and methods:
Example
<?php
class
Car {
function Car() {
$this->model = "VW";
}}
$herbie = new Car(); // create an object
echo $herbie->model; // show object properties
?>
Output: VW
NULL:
NULL is a special data type that only has one value: NULL. To give a variable the
NULLvalue, simply assign it like this −
Ex: $my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case
26
insensitive;you could just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties −
It evaluates to FALSE in a Boolean context.
Example:
<?php
$x = "Hello world!";
$x = null; var_dump($x);
?>
PHP Resource:
The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP. A common example of using the resource data type is a database call.
Resources are handlers to opened files, database connections or image canvas areas.
constant() function
As indicated by the name, this function will return the value of the constant. This is useful when you
want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or
returned by a function.constant()
Example:
<?php define("MINSIZE",50);
echo MINSIZE;
echo constant("MINSIZE");// same thing as the previous line
?>
Output: 50 50
Operators:
27
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. PHP language supports following type of operators.
Arithmetic Operators:
There are following arithmetic operators supported by PHP language: Assume variable A holds 10
and variable B holds 20 then
28
Operators Description Example
Increment/Decrement operators:
-- Decrement operator, decreases integer value by one $A-- will give 9 / --$A
Comparison Operators:
There are following comparison operators supported by PHP language Assume variable A
holds 10 and variable B holds 20 then:
== Checks if the value of two operands are equal or not ($A==$B) is not true.
!= Checks if the values of two operands are equal or not, ($A != $B) is true.
if values are not equal then condition becomes true.
29
> Checks if the value of left operand is greater than the ($A >$B) is not true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or ($A >= $B) is not true.
equal to the value of right operand, if yes then returns
true.
<= Checks if the value of left operand is less than or equal ($A <= $B) is true.
to the value of right operand, if yes then condition
Logical Operators:
There are following logical operators supported by PHP language Assume variable A holds 10
and variable B holds 20 then:
Operator Description Example
and (or) && Called Logical AND operator. If both the operands ($A and$B) is true.
are true then then condition becomes true.
($A &&$B) is true.
or (or) || Called Logical OR Operator. If any of the two ($A or$B) is true.
operands are non zero then then condition becomes
true. ($A || $B) is true.
Assignment Operators:
There are following assignment operators supported by PHP language:
30
+= Add AND assignment operator, It adds right operand $C += $A is equivalent
to the left operand and assign the result to left operand to $C = $C + $A
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
result of the evaluation.
String Operators:
PHP has two operators that are specially designed for strings.
31
Array Operators:
The PHP array operators are used to compare arrays.
Operator Description Example
=== Identity $x === $y (Returns true if $x and $y have the same key/value
pairs in the same order and of the same types)
32
Control Structures:
The if, elseif ...else and switch statements are used to take decision based on the different condition. You can
use conditional statements in your code to make your decisions. PHP supports following three decision
making statements –
If you want to execute some code if a condition is true and another code if a condition is false,
use the if-else statement.
If you want to execute some code if one of the several conditions is true use the elseif
statement
33
34
Syntax
EX: <html>
if (condition)
<body>
code to be executed if condition is true; <?php
elseif (condition)
$d=date("D");
code to be executed if condition is true;
if($d=="Fri")
else echo"Have a nice weekend!";
code to be executed if condition is false; elseif($d=="Sun")
Example echo"Have a nice Sunday!";
The following example will output "Have a else
nice weekend!" if the current day is Friday, echo"Have a nice day!";
and "Have a nice Sunday!" if the current day
is Sunday. Otherwise, it will output "Have a ?>
nice day!" </body>
</html>
Syntax Example
switch (expression) The switch statement works in an unusual
way. First it evaluates given expression
{
then seeks a lable to match the resulting
case label1:
value. If a matching value is found then the
code to be executed if expression = label1;
code associated with the matching label
break;
will be executed or if none of the lable
case label2:
code to be executed if expression = label2; matches then statement will execute any
break; specified default code.
default:
code to be executed
if expression is different
from both label1 and label2;
}
35
Loop Types:
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.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
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;
for( $i=0; $i<5; $i++)
$a +=10;
$b +=5;
}
echo("At the end of the loop a=$a and b=$b");
?></body></html>
This will produce the following result –
At the end of the loop a=50 and b=25
36
The while loop statement:
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.
37
Syntax
while (condition)
{
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++;
}
echo("Loop stopped at i = $i and num = $num");
?></body></html>
Syntax
do
{
code to be executed;
}while (condition);
38
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 −
39
while( $i <10){
$i++;
if( $i ==3)break;}
40
the code that the loop executes, preceded by a conditional test. For the
pass encountering continue statement, rest of the loop code is skipped
and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true
it just skip the code and next value is printed.
<html>
<body>
<?php
$nos=array(1,2,3,4,5);
foreach( $nosas $value )
{
if( $value ==3) This will produce the following result −
continue;
Value is 1
echo"Value is $value <br />";
Value is 2
}
Value is 4
?>
Value is 5
</body>
</html>
Functions:
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 –
Creating a PHP Function
Calling a PHP Function
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.
Creating PHP Function
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.
41
<html><head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
functionwriteMessage()
{
echo"Have a nice time Kalpana!";
}/* Calling a PHP Function */
writeMessage();
Output: Have a nice time Kalpana!
?>
</body>
</html>
PHP Functions with Parameters:
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters you’re 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
functionaddFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo"Sum of the two numbers is : $sum";
} of the two numbers is : 30
Output: Sum
addFunction(10,20);
?></body></html>
It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value. Any
changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in
either the function call or the function definition.
42
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
functionaddFive($num)
{
43
$num+=5;
}
functionaddSix(&$num)
{
$num+=6;
}
$orignum=10;
addFive( $orignum);
echo"Original Value is $orignum<br />";
addSix( $orignum);
echo"Original Value is $orignum<br />";
Output: Original Value is 10
?>
</body> Original Value is 16
</html>
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).
<html><head><title>Writing PHP Function which returns value</title></head>
<body>
<?php
functionaddFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value=addFunction(10,20);
Output:Returned value from the function : 30
echo"Returned value from the function : $return_value";
Setting Default Values for Function Parameters
?></body></html>
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
44
<html><head><title>Writing PHP Function which returns value</title></head>
<body>
<?php
functionprintMe($param= NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
Output:This is test
</body></html>
45
Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables
exactly as you would the function name itself.
<html> <html>
<head> <head>
<title>Dynamic Function <title>Dynamic Function
Calls</title></head> Calls</title></head>
<body> <body>
<?php <?php
functionsayHello()
function add($x,$y)
{
{
echo "Hello<br />";
echo"addition=" . ($x+$y);
}
}
$function_holder="sayHello";
$function_holder="add";
$function_holder();
$function_holder(20,30);
?></body></html>
Output:Hello ?></body></html>
Output:addition=50
PHP Default Argument Value:
The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight \t";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
O/P: 35050 135 80
MVC Framework:
The Model-View-Controller (MVC) is an architectural pattern that separates an application into
three main logical components: the model, the view, and the controller. Each of these components
are built to handle specific development aspects of an application. MVC is one of the most
46
frequently used industry-standard web development framework to create scalable and extensible
projects
MVC Components:
47
Following are the components of MVC −
Model:
The Model component corresponds to all the data-related logic that the user works with. This can
represent either the data that is being transferred between the View and Controller components or any
other business logic-related data. For example, a Customer object will retrieve the customer
information from the database, manipulate it and update it data back to the database or use it to render
data.
View:
The View component is used for all the UI logic of the application. For example, the Customer
view will include all the UI components such as text boxes, dropdowns, etc. that the final user
interacts with.
Controller:
Controllers act as an interface between Model and View components to process all the
business logic and incoming requests, manipulate data using the Model component and interact
with the Views to render the final output. For example, the Customer controller will handle all the
interactions and inputs from the Customer View and update the database using the Customer Model.
The same controller will be used to view the Customer data.
48
Once you are comfortable with the way MVC frameworks work, you should move on to the mature
and already tested frameworks.
49
The table below briefly describes some of the popular php frameworks and the features that
each framework offers.
Framework Description
It is one of the most popular PHP MVC frameworks. It’s lightweight and has d
earni
a short l rich set of libraries that help build websites and applications rapidly.
kn
CodeIgniter
Users with limite programming can also use it. CodeIgniter powered
applications include
It’s a Hierarchical Model View Controller HMVC secure and lightweightIt ha
framework. components for developing applications rapidly. Companies that
Kohana
use Kohana include;
CakePHP It is modeled after Ruby on rails. It’s known for concepts such as softwareerns,
design patt configuration, ActiveRecord etc. CakePHP powered applications
include;
50
It is a powerful framework that is;
Zend It features APIs from vendors like Amazon, Google, Flickr, Yahoo etc. It’s
velo
ideal for deapplications. Zend powered applications include;
Pimcore CMS,
DotKernel.
BBC
Cisco
Webex
Offers.com
51
UNIT – II
Servlets: Introduction to Servlets, Benefits of Servlets, use as controller in MVC, servlet
lifecycle, basic HTTP, Reading Servlet parameters, Servlet session, Cookies, Servlets API
JDBC: JDBC Architecture, JDBC API, Connecting to a Database Using JDBC
INTRODUCTION TO SERVLETS:
Servlets:
• Servlets are server side programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser and databases or
applications on the 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.
• Servlets don’t fork new process for each request, instead a new thread is created.
• Servlets are loaded and ready for each request.
• The same servlet can handle many requests simultaneously.
Benefits of Servlets:
1. Better performance: because it creates a thread for each request, not process.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.
52
4. Secure: because it uses java language
53
Use as Controller in MVC:
The Model-View-Controller (MVC) is an architectural pattern that separates an application into three
main logical components: the model, the view, and the controller. Each of these components are built to
handle specific development aspects of an application. MVC is one of the most frequently used industry-
standard web development framework to create scalable and extensible projects.
MVC Components:
Following are the components of MVC:
Model:
The Model component corresponds to all the data-related logic that the user works with. This can
represent either the data that is being transferred between the View and Controller components or any other
business logic-related data. For example, a Customer object will retrieve the customer information from the
database, manipulate it and update it data back to the database or use it to render data.
View:
The View component is used for all the UI logic of the application. For example, the Customer view
will include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with.
Controller:
Controllers act as an interface between Model and View components to process all the business logic
and incoming requests, manipulate data using the Model component and interact with the Views to render
the final output. For example, the Customer controller will handle all the interactions and inputs from the
Customer View and update the database using the Customer Model. The same controller will be used to
view the Customer data.
54
Life Cycle of Servlet:
Steps:
The sequence in which the Web container calls the life cycle methods of a servlet is:
1. The Web container loads the servlet class and creates one or more instances of the
servlet class.
2. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
55
3. The Web container invokes the service() method to allow a servlet to process a client
request.
4. The service() method processes the request and returns the response back to the Web
container.
5. The Web container loads the servlet class and creates one or more instances of the
servlet class.
6. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
7. The Web container invokes the service() method to allow a servlet to process a client
request.
8. The service() method processes the request and returns the response back to the Web
container.
9. The Web container loads the servlet class and creates one or more instances of the
servlet class.
10. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
11. The Web container invokes the service() method to allow a servlet to process a client
request.
12. The service() method processes the request and returns the response back to the Web
container.
13. The Web container loads the servlet class and creates one or more instances of the
servlet class.
14. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
15. The Web container invokes the service() method to allow a servlet to process a client
request.
16. The service() method processes the request and returns the response back to the Web
container.
17. The servlet then waits to receive and process subsequent requests as explained in steps
3 and 4.
18. The Web container calls the destroy() method before removing the servlet instance
from the service. The destroy() method is also invoked only once in a servlet life cycle.
56
The init() method :
The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet.
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.
publicvoidinit()throwsServletException{
// Initialization code...
}
In the doGet() method, we can retrieve the client information of the HttpServletRequest
object. We can use the HttpServletResponse object to send the response back to the client.
publicvoiddoGet(HttpServletRequest request,
57
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
}
For example, if a client is entering registration data in an HTML form, the data can be
sent using the POST method.
To handle requests in a servlet that is sent using the POST method, we need to override
the doPost() method. In the doPost() method, we can process the request and send the
response back to the client.
publicvoiddoPost(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
}
58
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
Basic HTTP:
Reading Servlet Parameters (or) Handling HTTPRequest and HTTPResponse
The parameters are the way in which a client or user can send information to the Http
Server.
The HttpServletResponse Interface provides functionality for sending response to client.
The browser uses two methods to pass this information to web server. These methods are
GET Method and POST Method.
GET 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/hello?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server.
Never use the GET method if you have password or other sensitive information to pass to
the server.
The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable.
59
Servlet handles this type of requests using doGet() method.
POST method:
A generally more reliable method of passing information to a backend program is the
POST method.
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.
Session:
HttpSession object is used to store entire session with a specific client.
We can store, retrieve and remove attribute from HttpSession object.
Any servlet can have access to HttpSession object throughout the getSession() method of
the HttpServletRequest object.
HTTPServlet
HttpServlet is extends from GenericServlet and does not override init, destroy and other
methods.
It implements the service () method which is abstract method in GenericServlet.
A subclass of HttpServlet must override at least one method, usually one of these:
o doGet(), if the servlet supports HTTP GET requests
o Init() and destroy(), to manage resources that are held for the life of the servlet
60
Cookie:
A cookie is a small piece of information that is persisted between the multiple client
requests.
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides
a lot of useful methods for cookies.
Servlet API:
Servlet API consists of two important packages that encapsulates all the important classes
and interface, namely :
1. javax.servlet
2. javax.servlet.http
1. javax.servlet
Interfaces
1. Servlet – Declares life cycle methods for a servlet.
2. ServletConfig – To get initialization parameters
3. ServletContext- To log events and access information
4. ServletRequest- To read data from a client request
5. ServletResponse – To write data from client response
Classes
1. GenericServlet – Implements Servlet and ServletConfig
2. ServletInputStream – Provides an input stream for reading client requests.
3. ServletOutputStream - Provides an output stream for writing
responses to a client.
4. ServletException – Indicates servlet error occurred.
5. UnavailableException - Indicates servlet is unavailable
61
Servlet Interface
62
It provides 3 life cycle methods that are used to initialize the servlet, to service the
requests, and to destroy the servlet and 2 non-life cycle methods.
Method Description
public void init(ServletConfigconfig) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void provides response for the incoming request.
service(ServletRequestrequest,ServletResponse It is invoked at each request by the web
response) container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.
public ServletConfiggetServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello KALPANA</b>");
out.print("</body></html>");
}
public void destroy(){
System.out.println("servlet is destroyed");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "copyright 2007-1010";
}
63
}
64
ServletConfig interface
• When the Web Container initializes a servlet, it creates a ServletConfig object for the
servlet.
• ServletConfig object is used to pass information to a servlet during initialization by getting
configuration information from web.xml(Deployment Descriptor).
Methods
ServletContext Interface
• For every Web application a ServletContext object is created by the web container.
• ServletContext object is used to get configuration information from Deployment
Descriptor(web.xml) which will be available to any servlet.
Methods:
• getAttribute(String name) - returns the container attribute with the given name
• getInitParameter(String name) - returns parameter value for the specified parameter name
• getInitParameterNames() - returns the names of the context's initialization parameters as
an Enumeration of String objects
• setAttribute(String name,Objectobj) - set an object with the given attribute name in the
application scope
• removeAttribute(String name) - removes the attribute with the specified name from the
application context
Servlet RequestInterface
Methods
65
• getAttribute(String name), removeAttribute(String name), setAttribute(String name,
Object o), getAttributeName() – used to store and retrieve an attribute from request.
• getParameter(String name) - returns value of parameter by name
• getParameterNames() - returns an enumeration of all parameter names
• getParameterValues(String name) - returns an array of String objects containing all of the
values the given request parameter has, or null if the parameter does not exist
66
Servlet ResponseInterface
• Servlet API provides ServletResponseto assist in sending response to client.
Methods
• getWriter()- returns a PrintWriter object that can send character text to the client.
• setContentType(String type)- sets the content type of the response being sent to the client
before sending the respond.
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except the service
method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Methods
67
file and a stack trace.
ServletInputStream Class
It provides stream to read binary data such as image etc. from the request object. It is an
abstract class.
The getInputStream() method of ServletRequest interface returns the instance of
ServletInputStream class
intreadLine(byte[] b, int off, intlen) it reads the input stream.
ServletOutputStream Class
It provides a stream to write binary data into the response. It is an abstract class.
The getOutputStream() method of ServletResponse interface returns the instance of
ServletOutputStream class.
ServletOutputStream class provides print() and println() methods that are overloaded.
68
2. javax.servlet.http
Interfaces
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
Classes
1. HttpServlet
2.Cookie
The HttpServletRequest breaks a request down into parsed elements, such as request URI,
query arguments and headers. Various get methods allow you to access different parts of
the request.
1. requestURI – URL sent by browser
2. Parameters -
The HttpServletRequest provides methods for accessing parameters of a request. The
methods getParameter(), getParameterValues()and getParameterNames() are offered as
69
ways to access the arguments.
3. Attributes –
The request object defines a method called getAttribute(). The servlet interface
provides this as a way to include extra information about the request that is not covered
by any of the other HttpServletRequest methods.
4. ServletInputStream –
The ServletInputStream is an InputStream that allows your servlets to read all of the
request’s input following the headers.
HTTPServletResponse Extends the ServletResponse interface and can perform these tasks
1. Set Response Codes –
The response code for a request is a numeric value that represents the status of the
response. For example, 200 represents a successful response, 404 represents a file not
found.
2. Set Headers –
Headers for the response can be set by calling setHeader, specifying the name and value
of the header to be set.
3. Send Redirects –
The sendRedirect method is used to issue a redirect to the browser, causing the browser
to issue a request to the specified URL. The URL passed to sendRedirect must be an
absolute URL—it must include protocol, machine, full path, and so on.
4. Set ServletOutputStream –
The ServletOutputStream is obtained by calling getOutputStream on the
HttpServletResponse. It is a subclass of OutputStream that contains a number of
convenient print and println methods.Data written to the ServletOutputStream goes
straight back to the browser.
70
JDBC:
JDBC Architecture:
Description:
1. Application: It is a java applet or a servlet that communicates with a datasource.
2. The JDBC API: The JDBC API allows Java programs to execute SQL statements
and retrieve results. Some of the important classes and interfaces defined in JDBC
API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses some
database-specific drivers to effectively connect enterprise applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a
JDBC driver that intelligently communicates with the respective data source.
JDBC API:
The Java Database Connectivity (JDBC) API provides universal data access from the Java
programming language. Using the JDBC API, you can access virtually any data source, from
relational databases to spreadsheets and flat files. JDBC technology also provides a common base on
which tools and alternate interfaces can be built.
java.sql
javax.sql
71
72
JDBC was designed to keep simple things simple. This means that the JDBC API makes
everyday database tasks, like simple SELECT statements, very easy.
Import a package java.sql.* : This package provides you set of all classes that enables a
network interface between the front end and back end database.
• DriverManager will create a Connection object.
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
1. Register the Driver class
2. Create connection
73
3. Create statement
4. Execute queries
5. Close connection
Class.forName("oracle.jdbc.driver.OracleDriver");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object:
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Syntax of close() method:
public void close()throws SQLException
Example to close connection:
con.close();
75
UNIT – III
Java Server Pages: Generating Dynamic Content, Using Scripting Elements, Implicit JSP
Objects. Conditional Processing – Displaying Values, setting attributes, Error Handling and
Debugging
76
JSP Scripting elements:
The scripting elements provides the ability to insert java code inside the jsp. There are three types of
scripting elements:
1. scriptlet tag
2. expression tag
3. declaration tag
1.JSP scriptlet tag:
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name:
In this example, we have created two files index.html and welcome.jsp. The index.html file gets the
username from the user and the welcome.jsp file prints the username with the welcome message.
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
77
out.print("welcome "+name);
%>
</form>
</body>
</html>
JSP expression tag:
The code placed within JSP expression tag is written to the output stream of the response. So you need
not write out.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression tag:
<%= statement %>
Example of JSP expression tag:
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
JSP Declaration Tag:
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag:
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Example of JSP declaration tag that declares field:
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method:
78
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.
<html>
<body>
<%!
Following table lists out the nine Implicit Objects that JSP supports –
1 Request
79
pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.
8 Page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
9 The Exception object allows the exception data to be accessed by designated JSP.
Conditional processing:
Sometimes to built the complex logic we require conditional statements. We can embed
JAVA conditional statements in JSP. This task can be done by scriptlets. The syntax for
scriptlets is:
<html>
<head><title>Introduction to scriptlet</title></head>
<body>
<h1>
</h1>
</body>
</html>
81
2. Expression language syntax error:
Expression language syntax error may occur due to:
Missing both curly braces
Missing end curly brace
Misspelled property name
Misspelled parameter name.
Sample program for error handling:
<%@ page language=”java” contentType=”text/html”>
<%@ page import=”java.util.*” %>
<html>
<body>Today’s date is: <%= new Date().toString() %>
</body>
</html>
82
UNIT – IV
Java Script: Introduction to JavaScript, Declaring Variables, Functions, Event Handlers
(onclick,onsubmit,etc…,) and Form Validation.
Spring Framework: Overview, Controllers, Handler Methods, and Developing Web Application Using
Spring.
Introduction to JavaScript:
JavaScript is the Programming Language for the Websites.
The first scripting language was introduced by Brendan Eich in 1996
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript can update and change both HTML and CSS.
JavaScript can calculate, manipulate and validate data.
Features of JavaScript:
There are following features of JavaScript:
All popular web browsers support JavaScript as they provide built-in execution environments.
JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
JavaScript is a weakly typed language, where certain types are implicitly cast (depending on
the operation).
JavaScript is an object-oriented programming language that uses prototypes rather than using
classes for inheritance.
It is a light-weighted and interpreted language.
It is a case-sensitive language.
JavaScript is supportable in several operating systems including, Windows, macOS, etc.
It provides good control to the users over the web browsers.
JavaScript – Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>
HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within the <head> tags.
Example:
83
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>
Declaring Variables:
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript :
local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
Name must start with a letter (a to z or A to Z),underscore( _ ), or dollar( $ ) sign.
After first letter we can use digits (0 to 9).
JavaScript variables are case sensitive, for example x and X are different variables.
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Variable Scope:
The scope of a variable is the region of your program in which it is defined. JavaScript variables have
only two scopes.
Global Variables:
A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function.
<script>
84
function abc(){
var x=10;//local variable
}
</script>
• A JavaScript local variable is declared inside block or function. It is accessible within the function or
block only.
global variable:
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable.
For example:
<script>
var data=200;
//gloabal variable
function a(){
document.writeln(“data from a function”data);
}
function b(){
document.writeln(“data from b function “+data);
}
a();//calling JavaScript function
b();
</script>
Functions:
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3)
{
// code to be executed }
Example:
85
<html>
<body>
<script>
function msg()
{
alert("hello! this is message");
}
</script>
86
the specific JavaScript that takes the action is called event handler.
Event handlers may be interactive or non interactive . when an event take place ,java script identifies the
event and execute its handler.
Java script events and their sources:
• Event handlers are embedded in documents as attributes of HTML tags to which you assign JavaScript
code to execute. The general syntax is
<TAG eventHandler="JavaScript Code">
where TAG is some HTML tag and EventHandler is the name of the event handler.
For example, the name of the attribute for the event click is onClick.
• <input type= “button” value =“clickMe” onClick= “alert(‘you cliked me’);”>
On click:
The onclick event occurs when the user clicks on an element.
In HTML:
<element onClick="myScript"
In JavaScript:
87
object.onClick = function(){myScript};
In JavaScript by using the addEventListener() method
object.addEventListener("click", myScript);
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onclick Event</h2>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script></body>
</html>
OnSubmit:
<html>
<head>
<title>submit demo</title>
</head>
<body>
88
<script language="JavaScript">
Function doCheck()
{
if(document.frmLogin.login.value == "")
{
alert('login field can never be blank');
return false;
}
if((document.frmLogin.password.value) == "")
{
alert('password field can never be blank');
return false;
}
// return true;
}
</script>
Form Validation:
• It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
• JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation.
• Most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
89
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
} </script>
<body>
<form name="myform" method="post" action="abc.html" onSubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
abc.html
<html>
<head>
<title>Valid User </title>
</head>
<body>
<h1>You are valid user</h1>
<p>Thanks for visiting our site</p>
</body>
</html>
90
➢ JEE is a core java that contains set of libraries and API’S.
➢ Developers develop application for business logic.
➢ EJB is used for developing business logic applications.
• Disadvantages:
➢ Implementation & usage of EJB is highly complex at initial version of JEE.
➢ It is poor performance.
➢ Due to drawback in EJB, we moved to Spring Framework.
➢ Spring Frame work is more convinent than EJB.
Controllers:
A Spring MVC is a Java framework which is used to build web applications.
➢ It follows the Model-View-Controller design pattern.
➢ A Spring MVC provides an solution to use MVC in spring framework by the help of
DispatcherServlet.
Model-View-Controller:
Model :
A model contains the data of the application. A data can be a single object or a collection of
objects.
Controller:
A controller contains the business logic of an application. Here, the @Controller annotation is
used to mark the class as the controller.
View:
A view represents the provided information in a particular format.
Handler methods:
org.springframework.web.servlet.HandlerMapping is a handler mapping interface
➢ controller class is executed when users hit a URL
The work of Handler Mapping is to find out the controller bean in respect to a URL.
➢ Spring built-in HandlerMapping implementations are:
1.BeanNameUrlHandlerMapping
2.SimpleUrlHandlerMapping
3.ControllerClassHandlerMapping
91
1.BeanNameUrlHandlerMapping
➢ BeanNameUrlHandlerMapping is the default URL handler used by Spring MVC
➢ That means if we do not specify any URL handler then the spring will automatically load
this URL handler and pass requested URls to BeanNameUrlHandlerMapping to get the
controller bean to be executed.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=https://www.springframework.org/schema/beans
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context-5.0.7.xsd">
<bean name="/display.html" class="com.java.controller.HelloController"/>
<bean id="urlHandler" class="org.springframework.web.servlet.handler.BeanNameUrlHa
ndlerMapping"/>
</beans>
2.SimpleUrlHandlerMapping:
➢ SimpleUrlHandlerMapping is a simple way to define URL mapping using a map or
property bean
➢ Mapping more than one URL to a single controller class is possible by using
SimpleUrlHandlerMapping
➢ Mapping more than one URL to a single controller is not a good way to work with
spring
➢ In this case we need to inject properties or map object that describes the mappings
between the request URL path and Controllers
3.ControllerClassNameHandlerMapping:
➢ ControllerClassNameHandlerMapping is to take the short name of the controller class,
remove the “Controller” suffix
Developing Web Application using Spring:
The simple steps to create the first spring application.
➢ To run this application, we are not using any IDE. We are simply using the command
92
prompt
➢ The simple steps to create the spring application:
1.create the class
2.create the xml file to provide the values
3.create the test class
4.Load the spring jar files
5.Run the test class
1) Create Java class
• This is the simple java bean class containing the name property only.
package com.javatpoint;
public class Student { private String name; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayInfo()
{
System.out.println("Hello: "+name);
}
}
93
</beans>
3) Create the test class
package com.java;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}
94
UNIT- V
Django: Introduction to Django, Django Architecture, Django Models & Database Backends,
Developing web application using Django
Introduction to Django:
Django is a Python-based web framework that allows you to quickly create efficient web
applications. It is also called batteries included framework because Django provides built-in
features for everything including Django Admin Interface, default database – SQLlite3, etc.
When you’re building a website, you always need a similar set of components: a way to
handle user authentication (signing up, signing in, signing out), a management panel for your
website, forms, a way to upload files, etc. Django gives you ready-made components to use
and that too for rapid development.
Why Django Framework ?
Django Architecture :
In the previous article, we learned the unique features of Django. Now, we will discuss about
Django architecture based on MVC pattern. We will be understanding the MVC pattern in
more detail. Django MVC architecture solves lots of problems which were there in the
traditional approach for web development.
We will understand the components of the MVC pattern that are Model, Views, and
Controller in detail.
95
1. Model
The Model is the part of the web-app which acts as a mediator between the website interface
and the database. In technical terms, it is the object which implements the logic for the
application’s data domain. There are times when the application may only take data in a
particular dataset, and directly send it to the view (UI component) without needing any
database then the dataset is considered as a model.
Although today if we want any kind of website we need to have some sort of database as we
must be requiring some user input even if we are creating a simple blog site.
The Model is the component which contains Business Logic in Django architecture.
For example:
When you sign up on any website you are actually sending information to the controller
which then transfers it to the models which in turn applies business logic on it and stores in
the database.
96
2. View
3. Controller
The controller as the name suggests is the main control component. What that means is,
the controller handles the user interaction and selects a view according to the model.
The main task of the controller is to select a view component according to the user
interaction and also applying the model component.
This architecture has lots of advantages and that’s why Django is also based on this
architecture. It takes the same model to an advanced level.
For example:
When we combine the two previous examples, then we can very clearly see that the
component which is actually selecting different views and transferring the data to the model’s
component is the controller.
Django Models:
➢ In Django, a model is a class which is used to contain essential fields and methods.
➢ Each model class maps to a single table in the database.
➢ Django Model is a subclass of django.db.models.Model
Register / Use Model:
After creating a model, register model into the INSTALLED_APPS inside settings.py.
For example: INSTALLED_APPS = [ #... 'appname', #...
Django Model Fields:
97
➢ The fields defined inside the Model class are the columns name of the mapped table.
➢ The fields name should not be python reserve words like clean, save or delete etc
EXAMPLE:
Django Model Fields first_name = models.CharField(max_length=50)
# for creating varchar column
release_date = models.DateField() # for creating date column
num_stars = models.IntegerField() # for creating integer column
Field Options:
Each field requires some arguments that are used to set column attributes.
For example:
CharField requires max_length to specify varchar database.
Django Model Example:
We created a model Student that contains the following code in models.py file.
//models.py
class Student(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
contact = models.IntegerField()
email = models.EmailField(max_length=50)
age = models.IntegerField()
Database Backends:
➢ The settings.py file contains all the project settings along with database connection details.
➢ By default, Django works with SQLite, database and allows configuring for other databases as
well.
➢ Database connectivity requires all the connection details such as database name, user
credentials, hostname drive name etc
Example:
We need to provide all connection details in the settings file.
The settings.py file of our project contains the following code for the database.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoApp',
'USER':'root', 'PASSWORD':'mysql',
98
'HOST':'localhost', 'PORT':'3306' }
}
Developing web application using Django:
To build a simple web application that shows a simple message. First, we will create a Django
project and inside that directory, we will create an application, where other operations will be
performed.
Creating a project: In order to create a new Django project, run the following django-admin
startproject command in the command prompt.
Now, go to the folder where the command prompt was being run from. There you can find a
new project directory that looks like this.
Inside the ‘website’ directory (root directory), you will see another directory with name
same as the root directory.
Creating an Application:
• Open the command prompt.
• Navigate to the directory where you have created the project
Run the following command to create an app inside the project directory
python manage.py startapp tutorial
Here, you will see what difference this command makes inside the project directory. There
is a new folder called ‘tutorial’ inside the ‘website’ directory.
Now, if you go inside the ‘tutorial’ application folder, you will see the following Python files
Django created for you to configure the application
99
100