nework bsc it

59
BSIT-52 (WEB PROGRAMMING) 5/30/2013 0 Comments CHAPTER-1 (INTRODUCTION TO WEB PROGRAMMING) 1. What is Web? What is the difference between Internet and Intranet? Answer: A Web is a complex network of international, cross platform, and cross cultural communicating devices, connected to each other without any ordering or pattern. Internet and Intranet are both networks. However, the Internet is a network of networks, involving all communicating devices over the Web. However, an Intranet is limited to the users, machines, and software programs of a specific organization. 2. Explain GET and POST briefly? Answer: The GET and POST methods are used to send an HTTP request to the Web server. The GET method is used to request a document from the server. For example: Get /Webdocs/index.html CRLF The POST method allows Web browsers to send an unlimited amount of data to a Web server by allowing them to tag it on to HTTP request headers as the message body. 3. Explain how HTTP is used in client/server system. Answer: HTTP is a request-response type protocol that specifies that a client will open a connection to a server and then send a request using a specific format. In the client server system, the client connects to and sends a request to a server using HTTP. The server then receives and parses the request of the client to send back the requested resource using HTTP again. For sending the response, the

Upload: amarchaudary

Post on 07-Feb-2016

222 views

Category:

Documents


0 download

DESCRIPTION

networking solved chapters

TRANSCRIPT

Page 1: nework bsc it

BSIT-52 (WEB PROGRAMMING)

5/30/2013 0 Comments

CHAPTER-1 (INTRODUCTION TO WEB PROGRAMMING)

1. What is Web? What is the difference between Internet and Intranet?

Answer: A Web is a complex network of international, cross platform, and cross cultural communicating devices, connected to each other without any ordering or pattern.

Internet and Intranet are both networks. However, the Internet is a network of networks, involving all communicating devices over the Web. However, an Intranet is limited to the users, machines, and software programs of a specific organization.

2. Explain GET and POST briefly?

Answer: The GET and POST methods are used to send an HTTP request to the Web server. The GET method is used to request a document from the server. For example:

Get /Webdocs/index.html CRLF

The POST method allows Web browsers to send an unlimited amount of data to a Web server by allowing them to tag it on to HTTP request headers as the message body.

3. Explain how HTTP is used in client/server system.

Answer: HTTP is a request-response type protocol that specifies that a client will open a connection to a server and then send a request using a specific format. In the client server system, the client connects to and sends a request to a server using HTTP. The server then receives and parses the request of the client to send back the requested resource using HTTP again. For sending the response, the server software accesses the server hardware and retrieves the requested document.

4. Discuss the difference between static and dynamic Web pages?

Answer: Static Web pages are not processed by the server and are sent as it is. These pages do not have any scripting logic and they cannot change according to client's request parameters. Dynamic Web pages are processed by the server and then the generated content is sent to the client. They may involve information from a database or some other information such as client's user name.

Page 2: nework bsc it

5. "HTML is the language of the Web”. Explain.

Answer: HTML is a markup language in which Web pages are defined. It is simplistic so that everyone can use it. It is truly the language of the Web.Browsers treat all content given to them as HTML. Also, most of the information on the Internet is in the HTML format. Servers generate the HTML content from the server side scripts and send it to the browsers.

6. Why do we require JavaScript and DHTML?

Answer: JavaScript and DHTML make Web pages more interactive. HTML can be used to only present information. It cannot process data and is therefore not interactive.

JavaScript can be used to write programs for creating interactive Web pages. For example, if a user leaves out a field in an online form, JavaScript can be used to prompt the user to enter a value in that field.

DHTML can be used to make the pages more interactive by allowing you set properties of Web pages and their look and feel.

7. Brief about role played by CGI programming in Web programming?

Answer: CGI opened the gates of more complex Web applications. It enabled developers to write scripts, which can communicate with server applications and databases. In addition, it enables developers to write scripts that could also parse client's input, process it, and present it in a user friendly way.

__________________SMALL___________

1. Name the popular languages for developing Web applications.

Answer: Some of the popular languages for developing Web applications are ASP, ASP.NET, JSP, PHP, and Perl.

2. What is W3C?

Answer: W3C or the World Wide Web Consortium is a non-profit organization, which establishes Internet standards. For more information visit http://www.w3c.org.

3. What is the difference between a scripting language and a programming language?

Page 3: nework bsc it

Answer: The main difference is that programming languages are generally compiled whereas scripting languages are interpreted.

4. What is Extranet?

Answer: Unlike Intranet, Extranet allows outside access to local resources.

CHAPTER-2 (HTML)

1. What is HTML?

Answer: HTML stands for Hypertext Markup Language. It is a layout and format defining language used to write Web pages. It allows you to:

Publish documents to the Internet in a platform independent format

Create links to related work from your document

Include graphics and multimedia data in your documents

Link to non-World Wide Web information resources on the Internet

2. Brief about HTML tags and Elements.

Answer: An HTML tag defines the markup for a particular content in an HTML page and is represented within angular brackets. A start tag is represented as <tag_name> and an end tag is represented as </tag_name>. Most tags in HTML are in pairs of start and end tag. Only some tags such as <br> do not have an end tag.

An element contains a start tag, an end tag, and the content, which is marked up by those tags. The content in an element may comprise of data as well as nested tags. For example, the following is an HTML element:

<body>

<p>This is a nested tag</p>

</body>

An HTML page starts and end with <HTML></HTML> tags, marking the beginning and end of an HTML page. A page can be divided into the header and the body. The <HEAD></HEAD> tags represent the former and contain header information, which is not displayed in the browser window. The <HEAD></HEAD> tags also contain the <TITLE></TITLE> tags, which contain the text that will be displayed in the title bar of the browser window when the page is opened.

Page 4: nework bsc it

The <BODY></BODY> tags comprise the body element of an HTML page. The content with the <BODY></BODY> tags is displayed in the browser window.

3. List down different classifications of tags with 2 examples tags for each category.

Answer: Tags can be classified as:

Tags for document structure: HTML and HEAD

Heading tags: TITLE and LINK

Block-level text elements: H1 through H6, P

Lists: OL and UL

4. Explain any 4 HTML tags with at least 4 attributes with example.

Answer: The <BODY> tag represents the body of an HTML page and contains the content to be displayed in the browser window. It has various attributes including:

A)BACKGROUND: Specifies an image to be displayed in the background of an HTML page. Its value can be an absolute URL or a relative URL.

B)BGCOLOR: Sets the color of the backgroud

C)TEXT: Sets the default color of normal text for the HTML page.

D)LINK: Sets the default color of unvisited links in an HTML page.

The <TABLE> tag is used to create tables in HTML pages. It has various attributes such as:

E)BORDER: Indicates the thickness, in pixels, of the border to be drawn around the table.

F)CELLPADDING: Determines the amount of space, in pixels, between individual cells in a table.

G) CEPPSPACING: Determines the amount of space, in pixels, between individual cells in a table.

H) WIDTH: Determines the width of the table.

The <IMG> tag inserts images in an HTML page. It has various attributes such as:

I) SRC: Path of the image to be displayed.

J) ALT: Alternative text to be displayed in case the image cannot be displayed.

K) LOWSRC: Path of a low resolution version of the image.

L) HEIGHT and WIDTH: Specifies the dimensions of the image.

Page 5: nework bsc it

The <HR> tag is used to draw a horizontal line in HTML pages. It has various attributes such as:

M) ALIGN: Specifies the horizontal alignment of the lines that do not span the whole page.

N) NOSHADE: Reproduces a solid black line that has no shading.

O) SIZE: Indicates the thickness of the line in pixels.

P )WIDTH: Defines the horizontal width of the line.

5. Write an example HTML page containing a table 4 X 3 and each row colored differently.

Answer: The following is an HTML page containing a table 4 X 3 and each row colored differently:

<html>

<head>

<title>Colored Table</title>

</head>

<body>

<table border="1" width="100%">

<tr bgcolor="#0000FF">

<td width="33%">&nbsp;</td>

<td width="33%">&nbsp;</td>

<td width="34%">&nbsp;</td>

</tr>

<tr bgcolor="#00A0FF">

<td width="33%">&nbsp;</td>

<td width="33%">&nbsp;</td>

<td width="34%">&nbsp;</td>

</tr>

<tr bgcolor="#AB00FF">

<td width="33%">&nbsp;</td>

<td width="33%">&nbsp;</td>

Page 6: nework bsc it

<td width="34%">&nbsp;</td>

</tr>

<tr bgcolor="#FB2CFF">

<td width="33%">&nbsp;</td>

<td width="33%">&nbsp;</td>

<td width="34%">&nbsp;</td>

</tr>

</table>

</body>

</html>

6. Write an HTML program to demonstrate text characteristics tags.

Answer: The following code demonstrates some of the important text characteristics tags in HTML:

<html>

<head>

<title>Text Characteristics</title>

</head>

<body>

<p><b> <font color = "#0000FF" face ="Arial" size = "5"> Text Characteristics in

</font>

<font color = "#0000FF" face ="Arial" size = "8">

<s>HTML</s>

</b>

</p>

</font>

<i>HTML</i> is a <em>formatting language</em> for Web pages. Below is an example of

<u>HTML code</u><br>

Page 7: nework bsc it

<code>

&lt;HTML&gt;<br>

&lt;HEAD&gt;<br>

&lt;/HEAD&gt;<br>

&lt;/HTML&gt;<br>

</code>

<p><kbd>&</kbd> followed by <kbd>gt</kbd> represents the greater than sign.

</body>

7. Write an HTML program to demonstrate applet embedding

Answer: Applets are embedded in HTML pages using the <APPLET> tag. An example of an HTML page containing an applet which scrolls the specified text across the screen at a specified speed, is given below: <HTML>

<HEAD>

<TITLE>Demo Applet</TITLE>

</HEAD>

<BODY>

<APPLET CODE="scrolling_banner.class: CODEBASE =jclasses

WIDTH = 240 HEIGHT = 400

ALIGN = ABSMIDDLE HSPACE = 10 VSPACE = 20>

<PARAM NAME = message VALUE = "Use Netscape Navigator to browse the World Wide Web.">

<PARAM NAME =speed VALUE = "4">

</APPLET>

</BODY>

</HTML>

8. Explain how you can embed an image in an HTML page.

Page 8: nework bsc it

Answer: To embed an image in an HTML page, you can use the <IMG> tag. The <IMG> tag includes various attributes, for embedding and formatting images in an HTML page. The most common attributes of the <IMG> tag are:

SRC: Absolute or relative path of the image to be embedded

LOWSRC: The path of the low resolution version the image

ALT: Alternate text to be displayed in case the image cannot be loaded.

ALIGN : Alignment of the image in the page

HEIGHT: Height of the image

WIDTH: Width of the image

You can use the above tags to load an image from a URL or a relative path. For example, if the image (suppose image_filename.gif) that you want to embed resides in the same folder as the HTML page, you can embed it as:

<IMG SRC="image_filename.gif" ALT = "this is an image loaded from a relative path">

The above will display the image in the file image_filename.gif. In case this image cannot be loaded, the text "this is an image loaded from a relative path" will be displayed.

Similarly, to load an image from a URL, you can specify the URL in the SRC attribute.

9. Create a simple HTML page to demonstrate usage of anchor tags.

Answer: The following HTML page, demonstrates the usage of anchor tags:

<html>

<head>

<title>Anchor Tag Characteristics</title>

</head>

<body>

<h1 align="center">All in One</h1>

<p align="left">In <A HREF= "#sec1">section 1</a> you can search. In <A HREF= "#sec2">section 2</a> you can shop.</p>

<A NAME= "sec1">Section 1:

Page 9: nework bsc it

</a>

<p>

<a href="http://google.co.in" target= "_blank">

Search on Google</a>&nbsp;</p>

<p><a href="http://yahoo.com">Search on Yahoo</a></p>

<p>&nbsp;</p>

<p>

<A NAME= "sec2">Section 2: </a>

</p>

<p><a href="http://ebay.com">

Shop on ebay&nbsp;</a></p>

<p><a href="http://wallpapers.com">Download wallpapers</a>&nbsp;</p>

<p><a href="http://t-shirts.com">

Order Custom T-Shirts

News</a></p>

</body>

</html>

10. Explain ordered list and unordered list.

Answer: Ordered lists are numbered list and represented by the <OL> tag in HTML. You can use the tag's TYPE and START attributes to change the style and sequence of the numbering in the list. The <LI> tag is used for individual items of the list. Ordered lists are usually used to represent procedures/sequence of steps in HTML pages. An example of an ordered list is give below:

To copy text in Word:

<OL>

<LI>Select the text.</LI>

<LI>Press Ctrl + C.</LI>

<LI>Click at the location where you want to past the text and pres Ctrl + V.</LI>

Page 10: nework bsc it

</OL>

The unordered list is a bulleted list and represented by the <UL> tag in HTML. You can use the tag's TYPE attribute to change the style of the bullets in the list. The <LI> tag is used for individual items of the list. Unordered lists are usually used to represent various items of a category or related to a topic. An example of an unordered list is given below:

The various types of domestic animals are:

<UL>

<LI>Dogs</LI>

<LI>Cats</LI>

<LI>Horses</LI>

</UL>

--------------------------------------------------------------------

1. What is <META> tag and why is it used?

Answer: <META> tag is a special tag, which is used to provide the information about the document under which it is embedded. It is primarily used for listing keywords and summary associated with a Web page. Search engine spiders use this information while indexing a page.

2. How can you include e-mail functionality in HTML pages?

Answer: Hyperlink to an email is created using anchor <a> tag itself but email address has to be preceded with mailto. For example,

<a href="mailto:[email protected]">Click to send mail</a>

Page 11: nework bsc it

This will create a hyperlink. When you click on this hyperlink, your default e-mail client will open with the specified address in the To field.

3. What is SGML?

Answer: SGML or Standardized Generalized Markup Language is, a language and a standard to define other markup languages. HTML is based upon it

4. Which other markup language are based on SGML

Answer: CML (Chemical Markup Language) provides tags that can be rendered as chemical symbols; MathML (Mathematical Markup Language) provides tags that can be rendered as mathematical expressions.

-----------------------------------------------------------

CHAPTER-3 (CREATING DYNAMIC WEB PAGES)

1. What is Java Script? List out uses of Java Script.?

Answer: JavaScript is a scripting language used to make interactive web pages. It is mostly used as a client side scripting language. Its uses include:

Control document appearance and content

Control the browser

Interact with document content

Interact with user

Read and write client state with cookies

Interact with applets

Manipulate embedded images

2. Create an HTML page, which pops up an alert message.

Answer: Following HTML pops up an alert message:

Page 12: nework bsc it

<html>

<head>

<title>Pop up</title>

</head>

<body>

<h1>Trying Pop-ups</h1>

<script language = "JavaScript">

alert("This is an alert message. It uses alert() in JavaScript");

</script>

</body>

</html>

3. Explain briefly about Cascading Style Sheets (CSS).

Answer: CSS controls the look and placement of elements on a page. With CSS you can set any style property of any element on a HTML page. One of the biggest advantages with CSS instead of regular way of changing the look of elements is that you can split content from design. You can, for instance, link a CSS file to all the pages in your site that sets the look of the pages. So if you want to change the elements on the page, such as font size of the main text, you can just change it in the CSS and all the pages will be updated.

The syntax of CSS code is:

<style type ="text/css">

ELEMENT [{property1:value1:property2:value2}]

</style>

Note that the style tag is always placed in the head of the document.

4. Explain the uses of script tags.

Page 13: nework bsc it

Answer: The script tag marks the beginning and end of JavaScript in a web page. You can specify the scripting language in the script tags' Language attribute. In addition, you can also specify where the script is expected to run using the runat attribute. For example, when JavaScript is used as a server side scripting language, you can use the script tag as:

<SCRIPT Language = "JavaScript" runat = "server">

</SCRIPT>

5. Explain Document Object Model.

Answer: The Document Object Model or DOM is the interface that allows you to programmatically access and manipulate content of a web page. It provides a structured, object-oriented, representation of the individual elements and content in a page with methods for retrieving and setting the properties of those objects. It also provides methods for adding and removing such objects, allowing you to create dynamic content.

The DOM also provides an interface for dealing with events, allowing you to capture and respond to user and browser actions.

6. Write a program to display text in status bar on click of a button.

Answer:

<html>

<head>

<title>Pop up</title>

</head>

<body onclick = "window.status = 'You have clicked!!!'">

<h1>Changing Status Bar Text</h1>

</body>

</html>

7. What is the difference between HTML and DHTML?

Page 14: nework bsc it

Answer: HTML is a markup language used to create static web pages. DHTML on the other hand is not a language by itself but a combination of different technologies such as HTML, CSS, JavaScript, and DOM. It is used to create dynamic pages.

8. Explain the methods to access nodes in a Document tree.

Answer: Following are the methods used to access a node in a document tree:

1.document.getElementById(): Returns the element or node whose ID is passed as a parameter to it.

2.document.getElementsByTagName(): Returns the list of nodes that have the tag passed to the function as a parameter.

9. What are text nodes?

Answer: If a node contains text, it is represented as a text node. For example, in<p id-node2>"This is the <b>initial</b>text.</p>, there are text nodes "This is the", "initial", and "text".

-------------------------------

1. Can JavaScript be run on the server?

Answer: Many Web servers support JavaScript as a server side scripting language. In this case, JavaScript can be executed on the server and not on client's browser. JavaScript (Jscript under IIS) is allowed to access server resources. If server side JavaScript is embedded in an HTML page then following tag definition should be used.

<script language="JavaScript" runat="server">

..

</script>

2. How can you declare array in JavaScript?

Answer: JavaScript has built in Array object, there are two ways for declaring an array:

1.var arr = new Array( array_length ); arr[ 0 ] = "one";

....

Arr[array_length - 1 ] = "somevalue";

Page 15: nework bsc it

2.var arr = new Array( "one", "two", "three" );

3. How can client's system date be obtained using JavaScript?

Answer: JavaScript has built in Date object for this. Following code will print current system date as dd/mm/yyyy <script >

var d = new Date()

document.write(d.getDate())

document.write("/")

document.write(d.getMonth() + 1)

document.write("/")

document.write(d.getFullYear())

</script>

4. How can you open a new browser window?

Answer: You can open a new browser window using the window.open(url, window name, attributes) method of JavaScript. Note that you can also open a hyperlink in a new window simply using HTML as:

<a href =www.yahoo.com target="_blank">

5. Using JavaScript how can you determine client's browser name and version?

Answer: JavaScript has navigator object to reference browser's property. Browser's name can be obtained using navigator.appName and its version can be obtained using navigator.appVersion.

__________________________________________

CHAPTER-4 (INTRODUCTION TO CGI)

Page 16: nework bsc it

1. What is CGI ?Give examples of CGI application and explain any one of them?

Answer: Common Gateway Interface is a specification, which allows Web users to run programs from their computers. CGI is not a programming language but rather a specification that allows programs and scripts written in other language to be run over the Internet.

2. What are CGI environment variables? Explain any five.

Answer: Most of the information about the client, server, and user input is placed and made available through globally accessible variables known as CGI environment variables. Some of the commonly used environment variables are:

QUERY_STRING: The query information passed to the program. It is appended to the URL with a ? when the browser sends it to the server. The name value pairs are then stored in this environment variable.

SERVER_PROTOCOL: The name of and revision of the information protocol that the request came in with.

REQUEST_METHOD: The method with which the information request was issued.

HTTP_USER_AGENT: The browser used by the client to issue the request.

CONTENT_LENGTH: The length of the data in bytes passed to the CGI program through the standard input.

3. Give difference between JavaScript and CGI programming.

Answer: JavaScript is a scripting language whereas CGI itself is a standard, which uses various other programming languages. JavaScript is used mainly on the client side whereas CGI programming is used to implement server side scripting. In addition, JavaScript is embedded in HTML documents whereas CGI programs reside in their own independent files.

4. Explain CGI.pm module with an example.

Answer: PERL supports various add-on modules, which are libraries of functions that perform specific tasks. These are called standard library modules. CGI.pm is a standard library module, which provides various functions. To include the CGI.pm module in your PERL script, you have to use the "use" command after the #!/perl/bin/perl line and before any other code:

use CGI qw(:standard);

Page 17: nework bsc it

After including CGI.pm you can call its functions such as header, which prints the Content-type header.

5. Explain different types of PERL variables

Answer: PERL variables are of the following three types:

Scalars: A scalar variable stores a single value of any type. Scalar variables are prefixed with a $. These variables need not be declared before using them. You can define or use a variable as:

$var =1;

$var_noval;

$str = "This is a scalar string variable";

Arrays: Arrays store an ordered list of values. Arrays can be declared as:

@emptyarr =();

@arr = ("1", "2","3");

Each individual item of an array is referred to by its index number as:

print "$arr[0]";

You can use the push() and pop() functions to insert or delete an element from an array.

Hashes: A Hash is a special kind of an array - an associative array or paired list of elements. Each pair in a Hash consists of a string key and data value. A hash is defined as:

%emptyhs = ();

%hs = ("key1", "val1", "key2", "val2");

or

%hs = (key1 => "val1",

key2=> "val2");

An individual item of a Hash is referred to as $hs{"key1"};

The my function can be used with each of the above type of variables to declare and limit the scope of the variable to the enclosing block as:

my $var;

Page 18: nework bsc it

6. Explain PERL control structures with appropriate examples.

Answer: PERL control structures include:

1.If-else and unless condition: This construct performs a Boolean test on an expression and performs actions based on the results of the Boolean test. For example:

If($var==1)

{

$out = "This was one";

}

elseif($var==0)

{

$out = "This was zero";

}

else

{

$out = "Was neither 0 nor 1";

}

print "$out";

The above code will print, "This was one" if the variable $var is 1. Otherwise, if $var is equal to 0, it will print "This was zero". If $var is nether 1 nor 0, it will print "Was neither 0 nor 1". Note that the else or elesif part is optional. You can also have a single if statement in your program or nested ifs and if-else or if-elseif-else structures.

Note that to compare strings you must use the eq operator. You can also join multiple conditions using the logical operators. Similar to the If command is the unless command. For example:

unless($var!=1)

{

Page 19: nework bsc it

$out = "This was one";

}

else

{

$out = "Not one";

}

Note that PERL does not support unlessif.

2.Foreach loop: It is used for iterating over a list of values. The elements of an array can be iterated over using foreach as:

Foreach my $i(@arr)

{

$arr[$i] = $i; //set the value of each element of array to its index number

}

3. For loop: It is used to repeatedly perform an action. It uses a three-part conditional consisting of the loop initializer, the loop condition, and the loop reinitializer. For example, to perform an action such as printing use the for loop as:

for($i=0;$i<10;$i++)

{

print "$i";

}

This will print numbers from 0 to 9.

4.While loop: It is also used to perform an action repeatedly as long as a Boolean expression evaluates to true as:

$i=0;

Page 20: nework bsc it

while ($i<10)

{

print "$i";

}

This will print numbers from 0 to 9.

5.Until loop: This performs the reverse action of the while loop. It executes as long as a Boolean expression is NOT true. For example:

$i=0;

until ($i>=10)

{

print "$i";

}

This will print numbers from 0 to 9.

7. What is Query String? Explain with an example.

Answer: The form data appended to a URL following a ? is called a query string. For example:

http://www.myweb.com?username=smith&password=juyhy

In the above URL, the form field 'username', whose value is 'smith', and field 'password' whose value is 'juyhy', are appended to the URL after '?'. They form the query string. Query string comprises of name-value pairs. Each name value pairs is separated by &. Spaces between values are encoded as + and other special characters are encoded as their ASCII value preceded by a %.

8. What are GET and POST methods? What is the difference between GET and POST Methods.

Answer: GET and POST are methods of sending data to the server for making it available to CGI programs. The GET method passes the information through environment variables whereas the POST method sends the data through standard input.

9. Write a simple CGI application, which accepts the user information and displays the Information entered to the user?

Page 21: nework bsc it

Answer:

#!/usr/bin/perl #print "Content-type:text/html\n\n";

#$form = $ENV{'QUERY_STRING'};

use CGI;

$cgi = new CGI;

print $cgi->header;

print $cgi->start_html( "Question Nine" );

$text = $cgi->param( 'text' );

if( $text )

{

print "You entered $text";

}

else

{

print '<form action="ques9.pl" method="get">';

print '<input name="text"><br>';

print '<input value="Submit"><br>';

print "</form>":

}

print $cgi->end_html;

Save the file as ‘ques9.pl’.

10. Write a CGI application that accepts 3 numbers from the users and displays the LCM of three numbers using GET and POST methods.

Answer:

Page 22: nework bsc it

#!/usr/bin/perl

#print "Content-type:text/html\n\n";

#$form = $ENV{'QUERY_STRING'};

use CGI;

$cgi = new CGI;

print $cgi->header;

print $cgi->start_html( "Question Ten" );

my $one = $cgi->param( 'one' );

my $two = $cgi->param( 'two' );

my $three = $cgi->param( 'three' );

if( $one && $two && $three )

{

$lcm = &findLCM( &findLCM( $one, $two ), $three );

print "LCM is $lcm";

}

else

{

print '<form action="ques10.pl" method="post"><pre>';

print 'Enter First Number <input name="one"><br>';

print 'Enter Second Number <input name="two"><br>';

print 'Enter Third Number <input name="three"><br>';

print '<input value="Submit"><br>';

print "</pre></form>";

}

print $cgi->end_html;

sub findLCM()

{

Page 23: nework bsc it

my $x = shift;

my $y = shift;

my $temp, $ans;

if ($x < $y) {

$temp = $y;

$y = $x;

$x = $temp;

}

$ans = $y;

$temp = 1;

while ($ans % $x)

{

$ans = $y * $temp;

$temp++ ;

}

return $ans;

}

Save the file as ‘ques10.pl’.

11. What is Extra Path information? Explain with an example.

Answer: Besides passing query information to a CGI script, you can also pass additional data known as extra path information as part of the URL. The server gauges where the CGI program name ends; anything following that is deemed as extra path information and stored in the PATH_INFO environment variable. For example the following line calls a script with extra path information: http://some.machine/cgi0bin/display.pl/cgi_doc.txt

____________________SMALL_______________

Page 24: nework bsc it

1. What is FastCGI?

Answer: FastCGI is an enhancement over CGI. Instead of creating a new process for every request, FastCGI uses the same process and queues requests to it. It saves lots of memory but it also forces user to wait for the previous requests to finish.

2. How can you embed output of a CGI script in a HTML document?

Answer: This can be done using exec directive. For example, following line will print output of addr.cgi

Your IP address is: <!--#exec cgi="path to addr.cgi""->

3. How can you open a file for writing and appending in PERL?

Answer: For opening a file to write, use:

open( FILE, ">" . file_name )

For opening a file to append, use:

open( FILE, ">>" . file_name )

4. How are functions defined in PERL? How are values passed to them?

Answer: Functions in PERL are defined by preceding them by keyword sub. For example:

sub hello {

print 'hello';

}

Variable passing is little tricky in PERL. As evident from the above example, functions do not take any parameters as input. Instead, arguments are passed in special array variable @_. This can be explained with the help of the following example make:

sub args

{

my ($msg) = @_;

Page 25: nework bsc it

print $msg;

}

args( "hello" );

5. What is local variable definition?

Answer: The keyword local can be used to define variables just as the my function. But it has a special meaning. It temporarily overwrites the global variable as long as the control is in its scope. Following PERL snippet will make things clear: $value = "hello";

sub printVal

{

print "value is $value";

}

sub localCheck

{

local $value = "Hi";

printVal();

}

printVal();

localCheck();

printVal();

Output will be

hello

hi

hello

_________________________________________________________

Page 26: nework bsc it

CHAPTER-5 (BASIC CONCEPTS OF WEB SERVERS)

1. What is Web Sever? Explain.

Answer: The Web server is the software responsible for accepting browsers' requests, retrieving the specified file or executing the script, and returning its content to the browser. Popular Web servers include Tomcat, Apache, and IIS.

2. List out differences between Web Server and Application Server.

Answer: The main differences between Web servers and application servers are:

A Web server is where Web components are deployed and run. An application server is where components that implement the business logic are deployed. For example, in a JSP-EJB Web application, the JSP pages will be deployed on the Web server whereas the EJB components will be deployed on the application servers.

A Web server usually supports only HTTP (and sometimes SMTP and FTP). However, an application server supports HTTP as well as various other protocols such as SOAP.

3. Explain the role of Deployment descriptors

Answer: A deployment descriptor is an XML document that defines all the components of an application along with related information such as initialization parameters and container managed security constraints that you want the server to enforce. This file helps the server to know crucial details about the application.

4. Briefly describe basic mechanism of Web server.

Answer: A Web server first retrieves a client request using Berkley sockets, which is a mechanism used for communicating over a network. The Web server listens for request on a particular port on the server machine. For HTTP request, this port is by default set to 80. When the server receives the request, it locates the document being requested. It looks for the file under the document root directory. For example, if the document root is /usr/local/httpd/htdocs and the client requests the document /staff/matthew.html, then the server retrieves /usr/local/httpd/htdocs/staff/matthew.html. If the URL does not specify a file but just a directory, the server returns the directory index file, generally called index.html or welcome.html.

The server sends the contents of the file back to the client, along with some HTTP response headers.

5. Explain the importance of Web.xml.

Page 27: nework bsc it

Answer: Web.xml is the deployment descriptor on Tomcat server. A deployment descriptor is an XML document that defines all the components of an application along with related information such as initialization parameters and container managed security constraints that you want the server to enforce. This file helps the server to know crucial details about the application. 6. Explain how servlet mappings are done in Web.xml.

Answer: Servlet Mapping is done in Web.xml with the help of the <servlet_mapping> tag as:

<servlet-mapping>

<servlet-name>Controller</servlet-name>

<url-pattern>*.do</url-pattern> </servlet-mapping>

<servlet-mapping>

<servlet-name>graph</servlet-name> <url-pattern>/graph</url-pattern>

</servlet-mapping> According to the first mapping, all requests of the form http://localshots:8080/{contextpath}.do will be mapped to the Controller servlet whereas according to second mapping all request of the form http://localshots:8080/{contextpath}/graph will be mapped to the graph servlet.

7. What is a war file? Give its importance.

Answer: WAR or Web Application Archive file is packaged servlet Web application. Servlet applications are usually distributed as a WAR files.

8. How can you specify session time out in Web.xml?

Answer: You can specify session timeout in the <session-timeout> attribute of the <session-config> element. For example, to specify a session timeout of 30 minutes use:

<session-config>

<session-timeout>30</session-timeout>

</session-config>

----------------------------------------------------

1. What is Ant? What are its major advantages?

Page 28: nework bsc it

Answer: Ant is a XML based automation tool. It is available freely from http://ant.apache.org. Using Ant, many tasks such as deploying, compiling, and packaging of Java application can easily be automated. Ant scripts are highly customizable.

2. How to package an application as WAR file? What are its advantages?

Answer: A WAR file is nothing but a compressed form of application's complete directory structure in a single file. It can be created using following command:

jar cvf Webapp.war

Execute the above command from root of Web application. WAR files make deployment and distribution easy.

3. How can you specify a custom error page for a particular server error?

Answer: This can be done by including following code in Web.xml. Error code is server's internal code. For different error codes, different pages can be specified.

<error-page>

<error-code>500</error-code>

<location>/error.jsp</location>

</error-page>

Whenever server generates "internal server error" /error.jsp will be displayed.

4. How to change default server port for Tomcat?

Answer: Tomcat by default listens on port 8080. Web browsers try to connect to port 80 by default. To change the server port for tomcat edit server.xml file. This file can be found under conf directory of tomcat's installation. Under the Service element in the server.xml file, change the value of the port attribute of thethe first Connector element to the desired port value.

5. What is a connection pool? List its advantages.

Answer: Connection pool is a set of database connections, which are shared among simultaneous users. It improves efficiency by manifolds. Connection pooling is also supported by Tomcat.

Page 29: nework bsc it

One of the major advantages of configuring a connection pool is that one can change backend without effecting code changes.

_______________________________________________________

CHAPTER-6 (JAVA SERVER PAGES (JSP))

1. What is JSP? How is it is different from CGI programming?

Answer: JSP is a technology for developing Web pages that include dynamic content. A JSP page contains standard markup language elements, such as HTML tags, just like a regular Web page. However, a JSP page also contains special JSP elements that allow the server to insert dynamic content in the page.

CGI is not an efficient solution for developing dynamic Web content. For every request, the Web server has to create a new operating system process, load an interpreter and a script, execute the script and then tear it all down again. This is taxing for the server and affects the scalability of the application.

However, in JSP, each JSP page is compiled into executable code on first request. On subsequent requests thee executable code is directly invoked instead of recompilation. This enables a server to handle JSP pages much faster than CGI programs.

2. Write a JSP programming which displays different message to the user based on the time of day.

Answer:

<%@ page content language="java" import="java.util.Calendar" %>

<html>

<head><title>Time Message</title></head>

<body>

<%

Calendar cal = Calendar.getInstance();

int hh = cal.get( Calendar.HOUR_OF_DAY );

String message = "";

Page 30: nework bsc it

if( hh < 12 )

{

message = "Good Morning!";

}

else if( hh == 12 )

{

message = "Good Noon!";

}

else if( hh > 12 && hh < 18 )

{

message = "Good Afternoon!";

}

else if( hh > 18 && hh < 21 )

{

message = "Good Evening!";

}

else

{

message = "Good Night!";

}

%>

<%=message%>

</body>

</html>

3. Explain JSP elements.

Page 31: nework bsc it

Answer: JSP elements are of 3 types

Directive: Specifies information about the page itself that remains the same between requests. For example, it can be used to specify whether session tracking is required or not, buffering requirements, and the name of the page that should be used to report errors.

Action: Performs some action based on information that is required at the exact time the JSP page is requested by a browser. An action, for instance, can access parameters sent with the request to lookup a database.

Scripting: Allows you to add small pieces of code in JSP page. These elements are also executed when a page is requested.

4. What are the advantages of JSP?

Answer: The advantages of JSP are:

Supports both scripting and element based dynamic content and allows programmers to develop custom tag libraries to satisfy application specific needs.

Are compiled for efficient server processing.

Can be sent in combination with servlets that handle the business logic of the model supported by Java servlet template engines.

It is specification not a product. Different vendors can launch and use different implementations of JSP, leading to competition for better quality and performance.

It is an integral part of J2EE, a complete platform for enterprise class applications.

5. How are JSPs better than Servlets?

Answer: Unlike servlets, JSP lets you separate presentation and business logic. You can place the HTML code (presentation) in JSP along with some dynamic elements. The business logic remains in the servlets or JavaBeAnswer: This approach helps to overcome the problems with a pure servlet based approach, such as:

Thorough Java programming knowledge is needed to develop and maintain all aspects of the application, since the processing code and the HTML elements are lumped together.

Changing the look and feel of the application, or adding support for a new type of client, requires the servlet code to be updated and recompiled.

It is hard to take advantage of Web-page development tools when designing the application interface. If such tools are used to develop the Web page layout, the generated HTML must than be manually embedded into servlet code. This process is time consuming and error prone.

Page 32: nework bsc it

6. Explain the various JSP Directives.

Answer: JSP directives are JSP elements that provide global information about a JSP page. The various JSP directives are:

page directive: Defines information that will globally affect the JSP containing the directive. The syntax of a page directive is: <%@ page {attribute = "value"}%>. The various possible attributes are language, extends, import, session, buffer, autoFlush, isThreadSafe, info, errorPage, isErrorPage, and contentType.

include directive: Used to insert text and/or code at the JSP translation time. Its syntax is: <%@ include file = "relativeURLspec" %>. The file attribute can reference a normal HTML file or a JSP file, which must be local to the Web application that contains the directive.

Taglib directive: States that the including page uses a custom tag library, uniquely identified by a URO and associated with a prefix that will distinguish each set of custom tags to be used in the page. Its syntax is: <%@ taglib uri = "tagLibraryURI" prefix = "tagPrefix"%>.

7. Explain JSP error handling.

Answer: The JSP architecture provides an error-handling solution through the use of JSPs that are written exclusively to handle JSP errors. The errors that occur most frequently are runtime errors that can arise either in the body of the JSP page or in some other object that is called from the body of the JSP page. Request-time errors that result in an exception being thrown can be caught and handled in the body of calling JSP, which signals the end of the error. Exceptions that are not handled in the calling JSP result in forwarding client request, including the uncaught exception, to an error page specified by the offsending JSP.

8. Explain implicit objects out, request, and response in a JSP page.

Answer: Following are the implicit objects in a JSP page:

out: This implicit object represents a JspWriter that provides a stream back to the requesting client. The most common method of this object is out.println(),which prints text that will be displayed in the client's browser.

request: This implicit object represents the javax.servlet.HttpServletRequest interface. The request object is associated with every HTTP request. One common use of the request object is to access request parameters. You can do this by calling the request object's getParameter() method with the parameter name you are seeking. It will return a string with the values matching the named parameter.

response: This implicit object represents the javax.servlet.HttpServletRequest object. The response object is used to pass data back to the requesting client. A common use of this object is writing HTML output back to the client browser.

Page 33: nework bsc it

_______________________SMALL__________________________

1. What is precompiling? How JSPs are pre-compiled in Tomcat?

Answer: By default JSPs are converted into their corresponding .java files when someone accesses them for the first time. This process involves lots of complex parsing and is slow. Precompiling automatically generates corresponding .java files without the need to visit the pages.

For precompiling under tomcat, use jspc command, under bin directory of tomcat installation as:

Jspc -d DIRJ -Webinc PATH_XML -Webapp PATH_JSP

Where, DIRJ is the directory where generated java files will be stored.

PATH_XML is an XML file in which servlet mappings will be stored

PATH_JSP is the source directory containing JSPs

2. What is JSTL?

Answer: JSTL or Java Server Pages Standard Tag Library is a freely available collection of custom tags, which provides various functionalities. Some of the tags are: tags to interact with databases; tags to iterate over collections; and tags for internationalization of dates and currencies.

3. How van you make the browser to reload the page every N number of seconds?

Answer: This can be done by adding Refresh header to response. The following JSP code can be used for this:

<%

response.addHeader( "Refresh", N );

%>

Page 34: nework bsc it

4. Which servers have support for JSP?

Answer: Weblogic, Resin, Sun Application Server.

________________________________________________________

CHAPTER-7 (SERVLETS)

1. What are servlets? Explain with an example?

Answer: Servlets are programs that run on a Web server and create Web pages on the fly. To be a servlet, a class should extend HttpServlet and override doGet or doPost or both methods, depending on whether data is sent by GET or POST. These methods take two arguments, HTTPServletRequest and HttpServletResponse. The HTTPServletRequest has methods that let you find out about incoming information such as FORM data and HTTP request headers. The HttpServletResponse has method that lets you specify the HTTP response line, response headers, and obtain a PrintWriter object, used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generated the desired page. A sample servlet is given below:

package hallo;

import java.io.*;

import javax.servlet.*;

import. Javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOexception {

PrintWriter out = response.getWriter();

Out.println("Hello World");

}

}

2. Explain Servlet life cycle.

Answer: The lifecycle of a servlet consists of the following main stages:

Page 35: nework bsc it

Instantiation: The Web server creates an instance of a servlet. This is based on a request or a container startup.

Initialization: The Web server creates the instance's init() method. When the Web server loads a Web application, it also loads the initialization parameters associated with the application. This and the previous step occur only once during the lifetime of a servlet.

Service: This is the third state in the servlet lifecycle. In this state, the servlet's service() method is called, which generates response. The generation of response involves the following steps:

a.Setting the content type of the response. The receiving application (browser) uses this information to know how to treat the response data. For example, to generate an HTML output, the content-type is set to "text html".

b.The second step is to get PrintWriter object from response. PrintWriter is a class that extends the java.io writer abstract class. In the case of servlets, the Web server constructs the Print Writer object from the java.io. OutputStream object associated with the underlying connection from the client. With TCP/IP based implementations, Web server usually gets OutputStream object from the socket, uses the object to create the PrintWriter object, and associates with the HttpServletResponse object. As a result, from within the servlet, you will able to write to object stream associated with the network association.

DESstroy: This is the final stage in a servlet lifecycle. In this stage, the destroy() method is called before shutting down the servlet.

3. What is the difference between HttpServlet and GenericServlet?

Answer: GenericServlet is the base class, which is extended by an abstract class HttpServlet.

4. What is the difference between doGet() and doPost().

Answer: doGet() needs to be overridden when the data is submitted to the server using the GET method whereas the doPost() method needs to be overridden when POST method is used to submit data to the server.

5. Explain the relationship between a servlet, its servlet container and the servlet API.

Answer: A servlet is a Java program, which runs in a servlet container and is written according to servlet API specification. Servlet API is a set of classes and interfaces, which outlines all necessary operations, restrictions, and behaviour for a servlet. A servlet container is software, which provides network services over which requests, responses are sent. It should provide abstraction in obtaining

Page 36: nework bsc it

requests and formatting responses and at least support communication over HTTP. For example, Tomcat is a servlet container.

6. Which two packages implement the Servlet API?

Answer: The two packages are:

1.javax.servlet

2.javax.servlet.http

7. Draw a class diagram to show the relationship between major classes in the servlet API.

Answer: The class diagram is shown as here:

Class Diagram

8. What are the advantages of using servlets to extend server functionality?

Answer: Following are the advantages of using servlets:

1.It helps to achieve platform independence.

2.It provides performance improvement as classes stays in the memory once called.

3.It is much more secure over traditional server side languages. For example, no problems of memory leakages and buffer overflows are faced in case of servlets.

4.It uses Java's multithreading capabilities, which gives it a performance gain.

9. Describe the request handling cycle and the methods invoked on the servlet by the servlet container.

Answer: Following are the operations done on a servlet by servlet container when a servlet is requested:

1.If servlet instance does not exist in memory, the container:

a.Loads the servlet class and thus creates its instance

b.Calls the init() method on the above class and passes ServletConfig as parameter

2.On any further request service() method of servlet class is called and HttpServletRequest and HttpServletResponse are passed as parameters to it.

Page 37: nework bsc it

10. Which class provides methods of reading the parameters submitted by a client?

Answer: There is no class for this but HttpServletRequest interface provides methods getParameter(), getParameterValues(), and getParameterMap() for obtaining parameters submitted by client.

11. Which class provides methods of reading the parameters specified in the deployment descriptor file?

Answer: ServletConfig class provides methods getInitParameter() and getInitParameterNames() for reading parameters specified in deployment descriptor.

12. Which streams are used for sending the contents of the entity-body in the response?

Answer: ServletOutputStream is used for sending contents in response, if the data is binary. It extends the OutputStream class. Its object is normally obtained by calling HttpServletResponse.getOutputStream.

For sending character data PrintWriter class is used, which extends the Writer class. Its object is obtained by calling the HttpServletResponse.getWriter() method.

13. Outline the main steps in implementing the servlet.

Answer: Following are the steps used in implementing a servlet for HTTP communication:

1.Import required servlet packages in the class.

2.Make the class extend HttpServlet.

3.Override methods doGet(), doPost(), or doService() as required by problem in hand.

4.Make an entry for the above servlet in deployment descriptor.

5.Configure any extra options or filters, which are required by the server to function.

14. Explain the semantics of the HTML FORM element.

Answer: The HTML form element represents a form in which users can input data and submit it to the server for processing. The HTML form tag is as follows:

<FORM NAME="name" ACTION = "action.jsp" METHOD = "POST/GET">

Page 38: nework bsc it

The name attribute specified the name for a form. The action attribute specified the URL of the document or the name of the file to which the form data is submitted for action and the method attribute specified the HTTP method through which the data is sent to the server.

The action attribute can be a simple static Web page or a servlet. The method can be POST or GET.

A form includes various other <INPUT> elements such as textbox, list, buttons, or checkboxes.

15. Which statements are true.

1.A web application can have more than web.xml.(FALSE)

2.The HTTPServlet class implements the ServletConfig interface.(TRUE)

3.The HTTPServlet class implements the ServletContext interface(FALSE)

4.In a doHttpServletMethodName( ) method, the request and the response objects can be manipulated in any order.(TRUE)

5.The servlet configuration can change from request to request. (FALSE)

6.The servlet context can change from request to request.(FALSE)

7.The servlet element must occur before the servlet-mapping in an element in web.xml file.(TRUE)

8. The servlet-class element must specify the full package name of the servlet class.(TRUE)

_______________SMALL___________________

1. How can you write messages in server log using servlet API? In Tomcat, logs are stored in which directory?

Answer: ServletContext can be used for logging messages to the server log. One of the major advantages of using logging is that while printing an exception, the complete stack trace is written in the log. Following snippet explains logging:

ServletContext con = getServletContext();

con.log( "logging is good" );

try

{

throw new Exception( "exception" );

}

Page 39: nework bsc it

catch( Exception e )

{

con.log( e ); //will write e.printStackTrace() in log

}

In Tomcat, logs are stored in logs directory.

2. While sending a file from a servlet response, which header should be set to tell the browser that it should prompt user to save this file and not to display it in browser window?

Answer: Content-Disposition header is required to be set for this purpose as:

response.addHeader( "Content-Disposition","attachment; filename=" + filename_to_save );

3. How are filters created? List some practical usage of filters.

Answer: Filters are created by implementing javax.servlet.Filter interface. Filters are chains, which are linked according to mapping in Web.xml. Application developer can make original request pass through various filters before making it reach targeted servlet.

Some of the cases in which filters can be of great help are:

Authentication

Compression

Parsing

Encoding - Decodin

4. How to obtain the query string in servlets?

Answer: If request type is GET, then name-value pairs are URL encoded and are appended after ? sign in front of the request URL. Query string or the content after the ? can be obtained by the request.getQueryString() method.

_______________________________________________________________

CHAPTER-8 (WORKINGWITH SESSIONS AND COOKIES)

Page 40: nework bsc it

1. What are the several ways of tracking users?

Answer: The several ways in which you can track users are: -Using hidden controls

-Using cookie

-Using sessions

-Using applications

2. Explain in brief how to use hidden controls in a web page? Give an example.

Answer: Using HTML, hidden controls are an easy way to store data in a Web page. You can store data in a hidden control and then refer to the value of control wherever required. Hidden controls are often used when you submit a form to itself. That is if your form's ACTION attribute is set to the same page which contains the form. In this case, every time the page loads you have to determine whether it is being loaded afresh or after a submission. For this, you can store a text value such as "DONE" in a hidden control SUBMIT_STATUS, and check for it whenever the page loads. If request.getParameter(SUBMIT_STATUS) returns a NULL value, it means that the form is being loaded afresh.

This logic is demonstrated in the following code:

<html>

<head></head>

<body>

<%

if(request.getParameter("DONE")==null)

{

out.println("You entered your name as:" + getParameter("name"));

}

else

{

%>

<form action = "this.jsp" method = "POST">

Page 41: nework bsc it

Enter your name:<input type ="text" name = "name"></input

<input type = "HIDDEN" name = "DONE" value ="submitted">

<input type = "SUBMIT" value = "SUBMIT">

</form>

<%

}

%>

</body>

</html>

3. What are the disadvantages of hidden controls?

Answer: The disadvantages of hidden controls are that they are not secure as any user can access the HTML source and view their value. Consequently, you cannot store crucial information such as passwords in them. In addition, they complicate the code many times.

4. What are cookies? Explain in brief.

Answer: Cookies are small text strings you store on a user's computer. Cookies store information for tracking users in name-value pairs. When you first visit a website it may store a cookie on your computer. Next, when you again visit the site it may read or manipulate the value of the cookie and perform an action based on it. For example, if a site allows you to customize the color of the user interface, it may set the color selected by you in a cookie on your computer and read the color value when next time you request the page of the website. The page can them be displayed in the color stored in the cookie.

5. List down any 6 methods of javax.servlet.http.Cookie class and their functionality.

Answer: Following are the methods of the Cookie class:

java.lang.String getName(): Returns the name of the cookie

java.lang.String getValue(): Returns the value of the cookie

void setValue(java.lang.String value): Assigns a new value to a cookie after it has been created

void setPath(java.lang.String uri): Sets the path for the cookie by which the browser will send the cookie

Page 42: nework bsc it

void setMaxAge(int expiry): Set the maximum age of the cookie in seconds

int getMaxAge(): Returns the maximum age of the cookie in second

6. List down any 6 methods of HttpServletResponse class and their functionality.

Answer: Following are the methods of the HttpServletResponse class:

int SC_ACCEPTED: Indicates that a request was accepted for processing but was not completed

int SC_BAD_GATEWAY: Indicates that the HTTP server received an invalid response from a server, when acting as a proxy or gateway

int SC_BAD_REQUEST: Indicates that the request sent by the client was incorrect

int SC_CONFLICT: Indicates that the request cannot be completed because of a conflict with the current state of the resource

int SC_CONTINUE: Indicates that the client can continue

7. Explain in brief how to create a cookie with an example.

Answer: You can create a cookie by instantiating an object of the Cookie class. For example, to create a cookie name 'mycookie', with the value 'this is the cookie value', you can use the following code snippet:

Cookie mycookie = new Cookie("mycookie", "this is the cookie value");

mycookie.setMaxAge(24*60*60);

respone.addCookie(mycookie)//install cookie on browser

The setMaxAge() method sets the time after which the cookie will expire. The response.addCooki() method will install the cookie on the browser.

8. Explain in brief how to read a cookie with an example.

Answer: You can read a cookie as:

Cookie[] cookies = request.getCookies();

for(int i=0;i<cookie.length;i++)

{

if(cookies[i].getName().equals("mycookie")

Page 43: nework bsc it

out.println("The value is" + cookie[i].getValue());

}

9. What is a session?

Answer: Sessions let you preserve data between accesses to a Web page by the same user. Unlike cookie, sessions are stored on the server itself in files or databases.

10. Explain in brief how to track a user using Sessions with an example.

Answer: You can track user using sessions by storing the details of his/her session with the Web site. For example, you store the number of times that a user has visited a page and display it to him on every visit. To track the user using sessions perform the following steps:

1.Include page directive with the session attribute set to true, at the top of the page, to indicate that a new session has to be started(if one does not already exist).

2.Check whether a count has already been set before in a session attribute using the getAttribute() method of the Session class.

3.If the count has not been set, the getAttribute() method will return null. In that case, you can create a new count value. If a value already exists, you can increment it and store the new value in the session object.

The above steps are implemented in the following code:

<%

Integer count = (Integer)session.getAttribute("visitcount");

If(count==null)

{count = new Integer(1);

}

else

{

count = new Integer(visitcount.intValue()+1);

}

session.setAttribute("visitcount", count);

%>

Page 44: nework bsc it

<body>

You have visited this page <%=count%> times.

</body>

11. What is the difference between Session and Application?

Answer: A single session allows you to track one user at a time whereas an application enables you to track all JSPs in the same site, regardless of the number of users accessing them.

12. Explain how to track users using SESSIONS, APPLICATIONS, AND JAVABEANSWER:

Answer: You can instruct Tomcat to save the JavaBeans in a session object as well as in attributes. You can store JavaBeans in applications as well. You do this with <jsp:useBean> element’s scope attribute, which you can set to one of these value: scope="page|request|session|application". The term scope indicates where a data item is visible in your code. The default scope for a bean is page scope, which means the bean exists only for the page scope. However, if you set the scope of a bean to a session, it is stored with the rest of session's data.

_____________SMALL_____________________

1. How can you set session time out programmatically? What is the advantage of it?

Answer: Session timeout can be set individually by calling setMaxInavtiveInterval( time_in_seconds ) on the HttpSession object of a particular session. Timeout setting in web.xml is universal. By using the above function call timeouts can be set according to user role.

2. What is SOAP call? What is its major advantage?

Answer: SOAP or Simple Object Access Protocol is used to transfer binary objects as xml based data over HTTP. Major advantage of SOAP calls is that they can be used in n-tier calls without making any tier mingle with other.

3. What is Locale? How can you obtain client's Locale in using servlet API?

Answer: Locale is the user's top preference for language stored in the browser. This information can be crucial for some web applications. For example, using this information, web application can provide interface elements in client's preferred language that is, it can behave like an automated multilingual software.

Page 45: nework bsc it

Using servlet API, Locale information can be obtained as an object of java.util.Locale. For this, call

Locale locale = request.getLocale()

To obtain the preferred language, call locale.getDisplayLanguage().

4. Is it possible to create an exception handling servlet such as JSP errorpage? Write the code for obtaining the thrown exception in a servlet.

Answer: Yes, if a servlet has ended prematurely with an exception thrown, filter can be put in to process it. Such filter can obtain thrown exception and error code by using

Throwable throwable = (Throwable)request.getAttribute("javax.servlet.error.exception");

Integer status_code = ((Integer)request.getAttribute("javax.servlet.error.status_code"));.

5. Explain a practical use of redirecting. How can you redirect a client using servlet API?

Answer: Redirecting is used in many phases of web application, logout module is one such phase. Here, all session information is invalidated, database connections are released, and client is then redirected to application's home page. To redirect a user using servlet, API uses:

response.sendRedirect( page_url_to_redirect );

Redirection causes client to send a request for the page specified as input in above call.

_____________________________________________________

CHAPTER-9 (ADVANCED TOPICS)

1. What is SSL? Why do you require SSL?

Answer: SSL or Secure Socket Layer is a protocol that authenticates Web sites to browsers. It is also used for encrypting communication between browser and Web servers. To enable SSL, you simply need to install digital certificates or Server ID.

Page 46: nework bsc it

The main role of SSL is to provide security for Web traffic. Security includes confidentiality, message integrity, and authentication. SSL achieves these elements of security through the use of cryptography, digital signatures, and certificates.

2. Explain SSL working.

Answer: SSL has two distinct entities, server and client. The client is the entity that initiates the transaction whereas the server is the entity that responds to the client and negotiates which cipher suites are used for encryption. In SSL, the Web browser is the client and the Web site server is the server. Three protocols lie within SSL, the Handshake protocol, the Record protocol, and the Alert protocol. The client authenticates the server during the Handshake protocol. When the session is initiated and the handshake is complete, the data transfer is encrypted during the Record Protocol phase. If there are any alarms at any point during the session, the alert is attached to the questionable packet and handled according to the Alert protocol.

3. What is XML? Explain in brief.

Answer: XML is a simple, common format for representing structured information as text. You can create your own tags to define and structure data, and transmit it. The basic syntax of XML is extremely simple. As with HTML, XML represents information as text using tags to add structure. A tag begins with a name in between angular brackets (<>). In XML, every tag must have a closing tag. An opening tag, closing tag and any content in between are collectively referred to as an element of an XML document. Elements can contain other elements but they must be properly nested. Elements can also contain text or a combination of elements and text.

4. Given an overview about EJBs.

Answer: Enterprise Java Beans (EJB) is a server-side component that executes specific business logic on a server when invoked by a local or remote client. EJB is actually a framework for writing distributed programs. It involves a standardization agreement that enables a component to run within any application server. The agreement is accomplished by implementing a set of Java interfaces from the EJB API. Note that EJBs are not GUI components.

5. What are the advantages and disadvantages of EJBs.

Answer: Following are the advantages of EJBs:

Many vendor application servers conform to the J2EE specification allowing you to select a best-of-breed solution.

To handle fluctuations in resource demand server-side resources can easily be scaled by adding or removing servers.

Page 47: nework bsc it

Application servers provide access to complex services, such as transaction and security management, resource pooling, JNDI (Java Naming and Directory Interface), and component lifecycle management.Following are the disadvantages of EJBs:

EJB has a large and complicated specification.

EJBs take time to develop. Also, they are difficult to debug. Occasionally, the bug may not be in your code but in the application server itself.

Frequently released newer versions of EJB specifications render application obsolete quickly.

6. Explain entity beans and session beans?

Answer: An entity bean is an object with the following special properties:

It is permanent. It does not get destroyed itself after a program finishes executing.

It is network-based. It can be used by any program over a network provided the program is able to access the bean on the networked machine.

It is executed remotely. Methods of an entity bean run on a server machine. When you call an entity bean's method, your program's thread stops executing and control passes over to the server. When the method returns from the server, the thread resumes execution.

It is identified by a primary key. Entity beans must have a primary key. The primary key is unique - each entity bean is uniquely identified by its primary key. For example, an employee entity bean may have Social Security number as primary key. You can only use entity beans when your objects have a unique identifier field or when you add such a field.

Session beans are different from entity beans in that they are not permanent objects. They are not shareable in general although it is possible to share them using handles. Session beans can be used to distribute and isolate processing tasks. Each session bean can be used to perform a certain task on behalf of its client. The tasks can be distributed on different machines. Session beans also do not have a primary key. Unlike entity beans, session beans are not primarily meant to be shared or found later.

7. Briefly describe the remote and home interfaces in EJBs?

Answer: A remote interface is the business end of EJB. It is the set of services provided by EJB.

The home interface is the book-keeping interface. It helps clients to create a new instance of an EJB, or to find an existing instance of an EJB. The methods used to find existing EJBs are shown as finder methods. Since session beans are not designed to be shareable, there are no session bean finder methods.

Page 48: nework bsc it

8. What is DTD?

Answer: DTD or Document Type Definitions is a document that contains grammar rules for validating an XML document. It is a schema specification method for XML.

__________________-SMALL-_____________________

1. What is JNDI?

Answer: JNDI or Java Naming and Directory Interface is a set of APIs that can be used to access the naming and directory services. Server side technologies such as EJB use JNDI for storing objects for later use and also for lookup operations.

2. What is XSLT?

Answer: XSLT or Extensible Stylesheet Language Transformation is used to convert either one xml document into another (such as a subset) or to convert xml data into presentable HTML page.

3. What is HTTPS? On which port it works by default?

Answer: HTTPS is HTTP + SSL. It is the secured communication channel that works by the rules of HTTP. By default it works on port 443.

4. What is EAR file?

Answer: EAR or Enterprise Archive is a J2EE file format that contains various components such as beans into an easy to deploy and compressed format.

5. What is a data island?

Answer: It is XML embedded inside HTML. They are used to store client side information and are used as a better alternative for hidden tags.

Page 49: nework bsc it

-----------------(END)------------------