WT Sem 3-2
WT Sem 3-2
Answers
1. PHP Data Types
A Data type is the classification of data into a category according to its attributes;
● Alphanumeric characters are classified as strings
● Whole numbers are classified integers
● Numbers with decimal points are classified as floating points.
● True or false values are classified as Boolean.
PHP is a loosely typed language; it does not have explicit defined data types. PHP
determines the data types by analyzing the attributes of data supplied.
1
?>
The output of the code above will be: 12.
Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The output of the code above will be: !dlrow olleH.
Arrays
2
An array stores multiple values in one single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what
if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by
referring to an index number.
3
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop,
like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
4
}
?>
==================================================================
3.
Functions
The real power of PHP comes from its functions; it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
● A function is a block of statements that can be used repeatedly in a program.
● A function will not execute immediately when a page loads.
● A function will be executed by a call to the function.
● Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code and the closing curly brace ( } )
indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name:
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a
variable.
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the
function, which outputs several different first names, but an equal last name:
5
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
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 <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
To let a function return a value, use the return statement:
Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
6
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
7
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
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!";
}
?>
PHP - The switch Statement
The switch statement will be explained in the next chapter.
The switch statement is used to perform different actions based on different conditions. 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;
8
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!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP while loops execute a block of code while the specified condition is true.
==================================================================
4. Validate Form Data With PHP
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a
text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
9
<script>location.href('http://www.hacked.com')</script>
We will also do two more things when the user submits the form:
● Strip unnecessary characters (extra space, tab, newline) from the user input data (with
the PHP trim() function)
● Remove backslashes (\) from the user input data (with the PHP stripslashes()
function)
● The next step is to create a function that will do all the checking for us (which is much
more convenient than writing the same code over and over again). We will name the
function test_input().
● Now, we can check each $_POST variable with the test_input() function, and the
script looks like this:
Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form
has been submitted - and it should be validated. If it has not been submitted, skip the
validation and display a blank form.
==================================================================
5. Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will send
the cookie too. With PHP, you can both create and retrieve cookie values.
10
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
11
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
12
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Sessions
A session is a way to store information (in variables) to be used across multiple pages. Unlike
a cookie, the information is not stored on the users computer.
When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does
not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color, etc). By default, session variables last until the user
closes the browser. So; Session variables hold information about one single user, and are
available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
13
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any
HTML tags.
14
Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it
scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a
new session.
==================================================================
15
6. File Handling
File handling is an important part of any web application. You often need to open and process
a file for different tasks.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks
like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows (the readfile()
function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
File Open/Read/Close
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function.
We will use the text file, "webdictionary.txt", during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hypertext Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
16
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
17
fclose($myfile);
?>
18
PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file
is created using the same function used to open files. If you use fopen() on a file that does not
exist, it will create it, given that the file is opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the
same directory where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open
an existing file for writing. All the existing data will be ERASED and we start with an
empty file.
In the example below we open our existing file "newfile.txt", and write some new data
into it:
Example
19
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
File Upload
With PHP, it is easy to upload files to the server. However, with ease comes danger, so
always be careful when allowing file uploads!
==================================================================
20
Unit-2
1. Create a DTD for User login page and wrote an XML document for the above DTD.
2. Create an XML Schema and XML document for User login page.
3. Write an XSLT program for book store application.
4. Differentiate DOM and SAX parsers.
5. Explain about DTD with example?
6. Explain about XML Schema with example?
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="username" type="xs:string"/>
<xs:element name="password" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
21
</xs:element>
</xs:schema>
employee.xml
<?xml version="1.0"?>
<employee
xmlns="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.javatpoint.com employee.xsd">
<username>vimal</username>
<password>jaiswal</password>
<email>[email protected]</email>
</employee>
==================================================================
3. PROGRAM:
bookstore.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="bookstore.xsl"?>
<bookstore>
<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005<you/year>
<price>29.99</price>
</book>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
bookstore.xsl
<xsl:stylesheet version="1.0” xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
22
<xsl:template match="/">
<html>
<body>
<h2> My Books collection</h2>
<table border="1">
<tr bgcolor="red">
<th align="left">title</th>
<th align="left">author</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 30">
<td bgcolor="yellow"><xsl:value-of select="author"/></td>
</xsl:when>
<xsl:when test="price > 10">
<td bgcolor="lightgreen"><xsl:value-of select="author"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="author"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
==================================================================
4.
DOM SAX
Both SAX and DOM are used to parse the XML document. Both has advantages and
disadvantages and can be used in our programming depending on the situation.
DOM stands for Document Object Model SAX stands for Simple API for XML Parsing
good for smaller size good to choose for larger size of file.
23
Stores the entire XML document into Parses node by node
memory before processing
SAX generally runs a little faster than SAX generally runs a little faster than DOM
DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself
otherwise DOM provided we have more memory.
==================================================================
5. 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 −
24
● DTD identifier is an identifier for the document type definition, which may be the
path to a file on the system or URL to a file on the internet. If the DTD is pointing to
external path, it is called External Subset.
● The square brackets [ ] enclose an optional list of entity declarations called Internal
Subset.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means, the declaration works independent of an external source.
Syntax
Following is the syntax of internal DTD −
Example
Following is a simple example of internal DTD −
<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.
25
<!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.
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.
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.
External DTD
In external DTD elements are declared outside the XML file. They are accessed by specifying
the system attributes which may be either the legal .dtd file or a valid URL. To refer it as
external DTD, standalone attribute in the XML declaration must be set as no. This means,
declaration includes information from the external source.
Syntax
Following is the syntax for external DTD −
Example
The following example shows external DTD usage −
26
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd is as shown −
Syntax
You need to declare a schema in your XML document as follows −
Example
The following example shows how to use schema −
The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
27
Elements
As we saw in the XML - Elements chapter, elements are the building blocks of XML
document. An element can be defined within an XSD as follows −
1. Simple Type
Simple type element is used only in the context of the text. Some of the predefined simple
types are: xs:integer, xs:boolean, xs:string, xs:date. For example −
3. Global Types
With the global type, you can define a single type in your document, which can be used by all
other references. For example, suppose you want to generalize the person and company for
different addresses of the company. In such case, you can define a general type as follows −
28
</xs:complexType>
</xs:element>
Now let us use this type in our example as follows −
Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
==================================================================
29
Unit-3
1. Define a servlet? Explain life cycle of a servlet. Illustrate with an example program.
Answers
1. Servlet:
Servlets are java programs that run on web or application servers, servlets are also called
server side programs i.e the code of the program executes at server side, acting as a middle
layer between request coming from Web browsers or other HTTP clients and databases or
applications on the HTTP server. A servlet container uses a Java Virtual Machine to run
servlet code as requested by a web server. A servlet dynamically loaded module that services
requests from Web server. It runs entirely inside the Java Virtual Machine.
The following are the task performed while implementing init() method
1. Reading initialization parameters using ServletConfig object
2. Initializing a database driver
3. Opening a database connection
4. Initialization of objects
service()
The service method handles all requests sent by a client. Each time the server receive a
request for a servlet, the server spawns a new thread and calls service method. The service
method checks the request type GET, POST, PUT, DELETE etc. For, every request to the
servlet, its service method is called. Two objects ServletRequest and ServletResponse are
passed as argument to it.
30
public void service(ServletRequest request, ServletResponse response ) throws
ServletException, IOException
destroy()
This method signifies the end of a servlet life. The resources that are previously allocated are
destroyed. The method is invoked by server administrator or programmatically by servlet
itself.
sum.html:
<html>
<body>
<form name="Form1" method="post" action="Add">
<table>
<tr>
<td><B>Enter First Number</td>
<td><input type=textbox name="Enter First Number" size="25"
value=""></td>
</tr>
31
<tr>
<td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25"
value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</form>
</body>
</html>
Add.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get printwriter.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer.parseInt(pvalue);
pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close();
}
}
32
==================================================================
3. HelloForm.java
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +
33
"<body>\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>"
);
}
}
Web.html
<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>
==================================================================
4.
Servlet API
Servlet API consists of two important packages that encapsulates all the important classes
and interface, namely :
● javax.servlet
● javax.servlet.http
INTERFACES CLASSES
Servlet ServletInputStream
34
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListener ServletContextEvent
RequestDispatcher ServletRequestAttributeEvent
SingleThreadModel ServletContextAttributeEvent
Filter ServletException
FilterConfig UnavailableException
FilterChain GenericServlet
ServletRequestListener
CLASSES INTERFACES
HttpServlet HttpServletRequest
HttpServletResponse HttpSessionAttributeListener
HttpSession HttpSessionListener
Cookie HttpSessionEvent
==================================================================
5. COOKIES
Cookies are small text files that are used to maintain the different session when a user online
for shopping different items from same web store. Cookies are send by the web server to the
35
client browser. The browser later return unchanged when visit the same web page again.
Once the web server receives cookie information the servlet program processes the cookie
information and recognizes it as a new user or already visited user. Cookies are therefore, a
accepted method used by the web server for session tracking. Since the enable web servers to
store and retrieve data from the client side. Cookies let a user to log in automatically. Cookies
can be used to remember user preferences
Example
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
36
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
==================================================================
6. Session Tracking:
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the
client opens a separate connection to the Web server and the server automatically does not
keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server −
37
Cookies
A web server 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 recieved 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.
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.
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.
URL rewriting is a better way to maintain sessions and it works even when browsers don't
support cookies. The drawback of URL rewriting is that you would have to generate every
URL dynamically to assign a session ID, even in case of a simple static HTML page.
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 −
38
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
39
Unit-4
1. Explain about Anatomy of JSP page
2. Write about JSP processing. Explain the components of JSP page?
3. Explain About implicit objects.
4. Differentiate JSP and Servlet and Explain JSP by taking suitable example?
5. Develop a JSP with a Bean in the application scope?
6. Explain cookies and session tracking of JSP by taking suitable examples?
Answers
1. Anatomy of JSP page:
● It is simply a regular web page with JSP elements.
● Everything in the page that is not a JSP element is called template text.
● This can be any text :- HTML, XML, WML or even plain text.
● When a JSP page request is processed, the template text and dynamic content
generated by the JSP elements are merged.
==================================================================
2. JSP processing
The following steps explain how the web server creates the Webpage using JSP −
1. As with a normal page, your browser sends an HTTP request to the web server. The
web server recognizes that the HTTP request is for a JSP page and forwards it to a
40
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
2. 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 behavior of the page.
3. The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
4. 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
furthur passed on to the web server by the servlet engine inside an HTTP response.
5. The web server forwards the HTTP response to your browser in terms of static HTML
content.
6. 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 −
JSP Components
In this section we will discuss about the elements of JSP.
Structure of JSP Page: JSPs are comprised of standard HTML tags and JSP tags. The
structure of JavaServer pages are simple and easily handled by the servlet engine. In addition
to HTML ,you can categorize JSPs as following -
● Directives
● Declarations
● Scriptlets
● Comments
● Expressions
Directives :
41
A directives tag always appears at the top of your JSP file. It is global definition sent to the
JSP engine. Directives contain special processing instructions for the web container. You can
import packages, define error handling pages or the session information of the JSP page.
Directives are defined by using <%@ and %> tags.
Declarations :
This tag is used for defining the functions and variables to be used in the JSP. This element of
JSPs contains the java variables and methods which you can call in expression block of JSP
page. Declarations are defined by using <%! and %> tags. Whatever you declare within these
tags will be visible to the rest of the page.
Scriptlets:
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine. Scriptlets can be used anywhere in the page. Scriptlets
are defined by using <% and %> tags.
Comments :
Comments help in understanding what is actually code doing. JSPs provides two types of
comments for putting comment in your page. First type of comment is for output comment
which is appeared in the output stream on the browser. It is written by using the <!-- and -->
tags.
Expressions :
Expressions in JSPs is used to output any data on the generated page. These data are
automatically converted to string and printed on the output stream. It is an instruction to the
web container for executing the code with in the expression and replace it with the resultant
output content. For writing expression in JSP, you can use <%= and %> tags.
42
These Objects are the Java objects that the JSP Container makes available to the developers
in each page and the developer can call them directly without being explicitly declared. JSP
Implicit Objects are also called pre-defined variables. Following table lists out the nine
Implicit Objects that JSP supports −
43
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to
send content in a response. The initial JspWriter object is instantiated differently depending
on whether the page is buffered or not. Buffering can be easily turned off by using the
buffered = 'false' attribute of the page directive.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class.
However, JspWriter has some additional methods designed to deal with buffering. Unlike the
PrintWriter object, JspWriter throws IOExceptions.
44
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also
supports more than 40 methods, about half of which are inherited from the
javax.servlet.jsp.JspContext class.
One of the important methods is removeAttribute. This method accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute
from all scopes, while the following code only removes it from the page scope −
pageContext.removeAttribute("attrName", PAGE_SCOPE);
JSP:
● It stands for Java Server Pages.
45
● It is a server side technology.
● It is used for creating web application.
● It is used to create dynamic web content.
● In this JSP tags are used to insert JAVA code into HTML pages.
● It is an advanced version of Servlet Technology.
● It is a Web based technology helps us to create dynamic and platform independent
web pages.
● In this, Java code can be inserted in HTML/ XML pages or both.
● JSP is first converted into servlet by JSP container before processing the client’s
request.
==================================================================
5. JavaBeans Example
Consider a student class with few properties −
package com.tutorialspoint;
public class StudentsBean implements java.io.Serializable {
private String firstName = null;
private String lastName = null;
private int age = 0;
public StudentsBean() {
}
46
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
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;
}
}
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.
<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 − −
47
The date/time is Thu Sep 30 11:18:11 GST 2010
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"/>
48
</p>
</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −
==================================================================
6. Cookies in JSP:
Cookies are text files stored on the client computer and they are kept for various information
tracking purposes. JSP transparently supports HTTP cookies using underlying servlet
technology.
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
<html>
<head>
<title>Setting Cookies</title>
49
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
50
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
51
</body>
</html>
==================================================================
52
Unit-5
1. Write a JavaScript program to check whether the given number is palindrome or not.
Show the result in an alert () dialog box.
2. Write a web page which prompts the user for six items of input ,stores this in an array
and display it using join (). Display the data in a sorted order.
3. Write a JavaScript program to handle mouse events.
4. Define javascript? Justify how javascript is Object oriented?
5. Write javascript function which will find the L.C.M. and G.C.D. of two numbers?
6. Explain about Document Object Model with example?
7. Write a program for form validation with example?
8. Explain about simple AJAX Application?
Answers
1.
<html>
<head>
<script type=text/javascript>
function Palindrome()
{
var rem, temp, final = 0;
var number = Number(document.getElementById("N").value);
temp = number;
while(number>0)
{
rem = number%10;
number = parseInt(number/10);
final = final*10+rem;
}
if(final==temp)
{
window.alert("The inputted number is Palindrome");
}
else
{
window.alert("The inputted number is not palindrome");
}
}
</script>
</head>
<body>
<br>
53
<h1>Whether a number is Palindrome or not</h1>
Enter The Number :<input type="text" name="n" id = "N"/><br>
<center><button onClick="Palindrome()">CHECK</button>
</body>
</html>
==================================================================
2.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
var x = 0;
var array = Array();
function add_element_to_array() {
array[x] = document.getElementById("text1").value;
alert("Element: " + array[x] + " Added at index " + x);
x++;
document.getElementById("text1").value = "";
}
function display_array() {
array.sort();
var e = "<hr/>";
for (var y=0; y<array.length; y++) {
e +=array[y] + " ";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</head>
<body>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
</input>
<input type="button" id="button2" value="Display" onclick="display_array();">
</input>
document.getElementById("Result").innerHTML = e;
</body>
</html>
==================================================================
54
3.
i. 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.
Example
Try the following example.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Output
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the web server. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
<html>
<head>
55
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
56
<h2> This is inside the division </h2>
</div>
</body>
</html>
Output
==================================================================
4. Javascript (JS) is a scripting languages, primarily used on the Web. It is used to enhance
HTML pages and is commonly found embedded in HTML code. JavaScript is an interpreted
language. Thus, it doesn't need to be compiled. JavaScript renders web pages in an interactive
and dynamic fashion. This allowing the pages to react to events, exhibit special effects,
accept variable text, validate data, create cookies, detect a user’s browser, etc.
Object-oriented (OO) languages usually are recognized through their use of classes for
creating various objects which have the equivalent properties and methods. It is to be noted
that, ECMA-Script has no concept of classes, and hence objects are different than in
class-based languages.
ECMA-262 describes and classifies an object as an "unordered collection of dissimilar
properties each of them having a primitive value, object, or function." Firmly speaking, this
means that an object is an array of all values in no specific order. Each property and/or
method is recognized by a name which is mapped to a value. For this reason, it thinks of
ECMA-Script objects as hash tables i.e., nothing more than a combination of name-value
pairs where the value may be data or a function. In this chapter, you will learn about
JavaScript Object oriented concepts.
The simplest way to create a custom object is to create a new instance of Object and add
properties and methods to it, as in the example mentioned below:
57
The previous example can be rewritten using literal object notation as follows:
var person = {
name: "Karlos",
age: 23,
job: "Network Engineer",
say_Name: function(){
alert(this.name);
}
};
The person object in the above example is equivalent to the person object in the prior
example mentioned earlier, with all those same properties and methods added. These
properties are all created with certain characteristics that define their behavior in JavaScript.
Object properties can be any of the three basic data types or any of the abstract data types.
Object properties are variables which are used within the object's methods, but as well can
be globally visible variables which are used throughout the page.
58
<script type=text/javascript>
function lcm_two_numbers(x, y) {
if ((typeof x !== 'number') || (typeof y !== 'number'))
return false;
return (!x || !y) ? 0 : Math.abs((x * y) / gcd_two_numbers(x, y));
}
function gcd_two_numbers(x, y) {
x = Math.abs(x);
y = Math.abs(y);
while(y) {
var t = y;
y = x % y;
x = t;
}
return x;
}
function gcd_lcm() {
a=Number(document.getElementById("a_input").value);
b=Number(document.getElementById("b_input").value);
console.log(lcm_two_numbers(a,b));
console.log(gcd_two_numbers(a,b));
}
</script>
</head>
<body>
Enter any Number: <input id="a_input">
Enter any Number: <input id="b_input">
<button onclick="gcd_lcm()">Find</button></br></br>
</body>
</html>
==================================================================
6. Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
The way a document content is accessed and modified is called the Document Object
Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies
to the organization of objects in a Web document.
59
JavaScript can access all the elements in a webpage making use of Document Object Model
(DOM). In fact, the web browser creates a DOM of the webpage when the page is loaded.
The DOM model is created as a tree of objects like this:
Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes,
change the existing elements and attributes and even remove existing elements and attributes.
JavaScript can also react to existing events and create new events in the page.
Example:
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<p>This is the welcome message.</p>
<h2>Technology</h2>
<p>This is the technology section.</p>
<script type="text/javascript">
var text = document.getElementById("one").innerHTML;
alert("The first heading is " + text);
</script>
</body>
</html>
==================================================================
60
7.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN(
document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {
61
}
return( true );
}
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
==================================================================
62
8. Ajax is the method of using JavaScript to send the client data on the server and then
retrieve it without refreshing the complete page. We can us the XMLHttpRequest object to
perform a GET or POST and then retrieve the server response without page refresh.
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function postRequest(strURL) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
}
63
}
xmlHttp.send(strURL);
}
function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}
function SayHello(){
var usr=window.document.f1.username.value;
var rnd = Math.random();
var url="sayhello.php?id="+rnd +"&usr="+usr;
postRequest(url);
}
</script>
</head>
<body>
<h1 align="center">Simple Ajax Example</h1>
<p align="center">Enter your name and then press "Say Hello Button"</p>
<form name="f1">
<p align="center">
Enter your name:
<input type="text" name="username" id="username">
<input value="Say Hello" type="button" onclick='JavaScript:SayHello()'
name="showdate">
</p>
<div id="result" align="center"></div>
</form>
<div id=result></div>
</body>
</html>
==================================================================
64