NIIT_ Solved Answers Bsc

download NIIT_ Solved Answers Bsc

of 25

Transcript of NIIT_ Solved Answers Bsc

  • 8/10/2019 NIIT_ Solved Answers Bsc

    1/25

  • 8/10/2019 NIIT_ Solved Answers Bsc

    2/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 2/25

    Ans.Static Web pages are not processed by the server and are sent as it is. These pages do not have any scripting logic and theycannot change according to client's request parameters. Dynamic Web pages are processed by the s erver and then the generatedcontent is sent t o the c lient. They may involve information from a database or some other information such as c lient's user name.

    5. "HTML is the language of the Web. Explain.? Ans.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 t o the browsers.

    6. Why do we require JavaScript and DHTML? Ans.

    JavaScript and DHTML make Web pages more interactive. HTML can be used to only present information. It cannot process dataand 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 onlineform, 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? Ans.CGI opened the gates of more complex Web applications. It enabled developers t o write sc ripts, which can communicate withserver 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.

    FAQ8. Name the popular languages for developing Web applications.

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

    9. What is W3C? Ans:W3C or the W orld Wide Web Consortium is a non-profit organization, which establishes Internet s tandards. For more informationvisit http://www.w3c.org.

    10. What is the difference between a scripting language and a programming language? Ans:The main difference is that programming languages are generally compiled whereas scripting languages are interpreted.

    11. What is Extranet? Ans:Unlike Intranet, Extranet allows outside access to local resources.

    12. Does HTTP support only two methods - Get and Post? Ans: No, HTTP also supports more methods. For example, it supports the HEAD method, which is similar to the GET method butdoes not return the message body in the response. It only returns the headers.----------------------------------------------------------------------------------------------------------

    Solutions t o Chapter Two Questions13. What is HTML?

    Ans.HTML st ands for Hypertext Markup Language. It is a layout and format defining language used to write Web pages. It allows you to:n Publish documents t o the Internet in a platform independent formatn Create links to related work from your documentn Include graphics and multimedia data in your documentsn Link to non-World Wide Web information resources on t he Internet

    14. Brief a bout HTML tags and Eleme nts. Ans. An HTML tag defines the markup for a particular content in an HTML page and is represented within angular brackets. A st art tag isrepresented as and an end tag is represented as . Most tags in HTML are in pairs of start and end tag.Only some tags such as
    do not have an end tag.

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

    This is a nested tag

    An HTML page starts and end with tags, marking the beginning and end of an HTML page. A page can be dividedinto the header and the body. The tags represent t he former and contain header information, which is notdisplayed in the browser window. The tags also contain the tags, which contain the text thatwill be displayed in the title bar of the browser window when the page is opened.The tags comprise the body element of an HTML page. The content with the tags isdisplayed in the browser window.

    15. List down different classifications of tags with 2 exa mples tags for each category. Ans.Tags can be classified as:n Tags for document structure: HTML and HEADn Heading tags: TITLE and LINK

    s-

    s-

    s-

    s-

    s-

    s-

    s-

    T

    REC

    T

    Twi

    Foll

    Em

    Tota

    1

    https://twitter.com/ss731382http://sslifehacker.blogspot.in/search/label/Tips%20and%20Trickshttp://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-64http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-63http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-62http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-61http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-54http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-53
  • 8/10/2019 NIIT_ Solved Answers Bsc

    3/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 3/25

    n Block-level text elements: H1 through H6, Pn Lists: OL and ULn Text characteristics: B, I , FONT

    16. Explain any 4 HTML tags with at least 4 attributes with example. Ans.The tag represents t he body of an HTML page and contains t he content t o be displayed in t he browser window. It hasvarious att ributes including:n BACKGROUND : Specifies an image to be displayed in the background of an HTML page. Its value can be an absolute URL or arelative URL.n BGCOLOR : Sets the color of the background.n TEXT : Set s t he default c olor of normal tex t for the HTML page.n LINK: S ets t he default color of unvisited links in an HTML page.

    The tag is used to create tables in HTML pages. It has various attributes such as:n BORDER : Indicates the thickness, in pixels, of the border to be drawn around the table.n CELLPADDING : Determines the amount of space, in pixels, between individual cells in a table.n CEPPSPACING : Determines the amount of space, in pixels, between individual cells in a table.n WIDTH : Determines the width of the table.The tag inserts images in an HTML page. It has various attributes such as:n SRC : Path of the image to be displayed.n ALT : Alternative text to be displayed in case the image cannot be displayed.n LOWSRC : Path of a low resolution version of the image.n HEIGHT and W IDTH : Specifies the dimensions of the image.The t ag is used to draw a horizontal line in HTML pages. It has various attributes such as:n 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.n SIZE : Indicates the thickness of the line in pixels.n WIDTH : Defines the horizontal width of t he line.

    17. Write an example HTML page containing a table 4 X 3 and each row colored differently. Ans.The following is an HTML page containing a table 4 X 3 and each row colored differently:Colored Table

    18. Write an HTML program to de monstrate text chara cteristics tags.

    Ans.The following code demonstrates some of the important text characteristics tags in HTML:Text Characteristics

    Text Characteristics inHTML

    HTML is a formatting language for Web pages. Below is an example of HTML code
  • 8/10/2019 NIIT_ Solved Answers Bsc

    4/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 4/25





    & followed by gt represents the greater than sign.

    19. Write an HTML program to demonstrate applet embedding. Ans. Applets are embedded in HTML pages using the 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:Demo Applet

  • 8/10/2019 NIIT_ Solved Answers Bsc

    5/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 5/25

    Select the text.Press Ctrl + C.Click at the location where you want to past the text and pres Ctrl + V.

    The unordered list is a bulleted list and represented by the tag in HTML. You can use the tag's TYPE attribute to change thestyle of the bullets in the list. The tag is used for individual items of the list. Unordered lists are usually used to representvarious 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:Dogs

    CatsHorses

    FAQ23. What i s tag and why is it used?

    Ans: tag is a special tag, which is used to provide the information about the document under which it is embedded. It isprimarily used for listing keywords and summary associated with a Web page. Search engine spiders use this information whileindexing a page.

    24. How can you include e-mail functionality in HTML pages? Ans:Hyperlink to an email is created using anchor tag itself but email address has to be preceded with mailto. For example, Click to send mailThis will create a hyperlink. When you click on this hyperlink, your default e-mail client will open with the specified address in theTo field.

    25. What i s SGML? Ans:SGML or Standardized Generalized Markup Language is, a language and a standard to define other markup languages. HTML isbased upon it

    26. Which other markup language are based on SGML? Ans:CML (Chemical Markup Language) provides tags that c an be rendered as chemical symbols; MathML (Mathematical MarkupLanguage) provides tags that c an be rendered as mathematical expressions.-----------------------------------------------------------------------------------------------------------

    Solutions t o Chapter Three Questions27. What is Java Script? List out uses of Java Script.?

    Ans.JavaScript is a scripting language used to make interactive web pages. It is mostly used as a client side scripting language. Itsuses include:n Control document appearance and contentn Control the browser n Interact with document contentn Interact with user n Read and write client state with cookiesn Interact with appletsn Manipulate embedded images

    28. Create an HTML page, which pops up an alert message. Ans.Following HTML pops up an alert message:Pop upTrying Pop-upsalert("This is an alert message. It uses alert() in JavaScript");

    29. Explain brie fly about Cascading Style She ets (CSS). Ans.CSS controls the look and placement of elements on a page. With CSS you can set any style property of any element on a HTMLpage. One of the biggest advantages with CSS instead of regular way of changing the look of elements is that you can split contentfrom 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 tochange 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 beupdated.The syntax of CSS code is:ELEMENT [{property1:value1:property2:value2}]

  • 8/10/2019 NIIT_ Solved Answers Bsc

    6/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 6/25

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

    30. Explain the uses of script tags. Ans.The script tag marks the beginning and end of JavaScript in a web page. You can specify the sc ripting language in the s cript t ags'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:

    31. Explain Document Object Model. Ans.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 t he properties of t hose objects. It also provides methods for adding and removing such objects , allowing you tocreate dynamic content.The DOM also provides an interface for dealing with events, allowing you to capture and respond to user and browser actions.

    32. Write a program to display text in status bar on click of a button. Ans.Pop upChanging Status Bar Text

    33. What is the difference between HTML and DHTML?

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

    34. Explain the methods to access nodes in a Document tree . Ans.Following are the methods used to access a node in a document tree:n document.getElementById() : Returns the element or node whose ID is passed as a parameter to it.n document.getElementsByTagName() : Returns the list of nodes that have the tag passed to the function as a parameter.

    35. What are text nodes? Ans.If a node contains text, it is represented as a text node. For example, in

    "This is the initialtext.

    , there aretext nodes "This is the", "initial", and "text".

    FAQ36. Can JavaScript be run on the server?

    Ans:Many Web s ervers support JavaScript as a server side s cripting language. In t his case, JavaScript can be executed on t he server and not on client's browser. JavaScript (Jscript under IIS) is allowed to access s erver resources. If server side JavaScript isembedded in an HTML page then following tag definition should be used....

    37. How can you declare array in JavaScript? Ans:JavaScript has built in Array object, t here are two ways for declaring an array:1. var arr = new Array( array_length );arr[ 0 ] = "one";....

    Arr[array_length - 1 ] = "s omevalue";2. var arr = new Array( "one", "two", "three" );

    38. How can clie nt's system da te be obtained using JavaScript? Ans:JavaScript has built in Date object for this. Following code will print current system date as dd/mm/yyyyvar d = new Date()document.write(d.getDate())document.write("/")document.write(d.getMonth() + 1)document.write("/")document.write(d.getFullYear())

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

  • 8/10/2019 NIIT_ Solved Answers Bsc

    7/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 7/25

    40. Using JavaScript how can you determine client's browser name and version? Ans:JavaScript has navigator object to reference browser's property. Browser's name can be obtained using navigator.appNameand its version can be obtained using navigator.appVersion.---------------------------------------------------------------------------------------------------------

    Solutions to Chapter Four Questions41. What is CGI ?Give examples of CGI application and explain any one of them?

    Ans.Common Gateway Interface is a specification, which allows Web users to run programs from their computers. CGI is not aprogramming language but rather a specification that allows programs and scripts written in other language to be run over theInternet.

    42. What are CGI environment variables? Explain any five. Ans.Most of the information about the c lient, s erver, and user i nput is placed and made available through globally access ible variablesknown as CGI environment variables. Some of the commonly used environment variables are:n QUERY_STRING : The query information passed to the program. It is appended to the URL with a ? when the browser sends it tothe server. The name value pairs are then stored in this environment variable.n SERVER_PROTOCOL : The name of and revision of the information protocol that the request came in with.n REQUEST_METHOD : The method with which the i nformation request was is sued.n HTTP_USER_AGENT : The browser used by the client to issue the request.n CONTENT_LENGTH : The length of the data in by tes passed to t he CGI program through the standard input.

    43. Give difference between JavaScript and CGI programming. Ans.JavaScript is a scripting language whereas CGI itself is a standard, which uses various other programming languages. JavaScript isused mainly on t he client s ide whereas CGI programming is used to implement s erver side sc ripting. In addition, JavaScript is

    embedded in HTML documents whereas CGI programs reside in their own independent files.

    44. Explain CGI.pm module with an example. Ans.PERL supports various add-on modules, which are libraries of functions that perform specific tasks . These are called st andardlibrary modules. CGI.pm is a standard library module, which provides various functions. To include the CGI.pm module in your PERLscript, you have to use the "use" command after the #!/perl/bin/perl line and before any other code:use CGI qw(:standard);

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

    45. Explain differe nt types of PERL variable s. Ans.PERL variables are of the following three types:n Scalars : A scalar variable stores a single value of any type. Scalar variables are prefixed with a $. These variables need not bedeclared before using them. You can define or use a variable as:$var =1;$var_noval;

    $str = "This is a scalar string variable";n 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 it s index number as:print "$arr[0]";You can use the push() and pop() functions to insert or delete an element from an array.n 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 astring 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 enclosingblock as:

    my $var;

    46. Explain PERL control structures with a ppropriate ex ample s. Ans.PERL control structures include:1. If-else a nd unless condition : This construct performs a Boolean test on an expression and performs actions based on theresults of the Boolean test. For example:If($var==1){ $out = "This was one";}elseif($var==0){$out = "This was zero";}else

  • 8/10/2019 NIIT_ Solved Answers Bsc

    8/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 8/25

    {$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){ $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 loopcondition, and the loop reinitializer. For example, to perform an action such as printing use the for loop as:for($i=0;$iheader;print $cgi->start_html( "Question Nine" );$text = $cgi->param( 'text' ); if( $text ) { print "You entered $text"; } else {

  • 8/10/2019 NIIT_ Solved Answers Bsc

    9/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 9/25

    print ''; print '
    '; print '
    ';

    print "";

    }print $cgi->end_html;Save the file as ques9.pl.

    NoteStudents need to know the IIS configuration for running perlapplications.

    50. Write a CGI a pplication that a ccepts 3 numbers from the users and displays the LCM of three numbers using GETand POST methods.

    Ans.#!/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 ''; print 'Enter First Number
    '; print 'Enter Second Number
    '; print 'Enter Third Number
    ';

    print '
    ';print "";

    }

    print $cgi->end_html;sub findLCM(){ 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.

    Note

    Students need to know the IIS configuration for running perlapplications.

    51. What is Extra Path information? Explain with an example. Ans.Besides passing query information to a CGI script, you can also pass additional data known as extra path information as part of theURL. The server gauges where the CGI program name ends; anything following that is deemed as extra path information and storedin 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

    FAQ52. What is FastCGI?

    Ans:FastCGI is an enhancement over CGI. Instead of creating a new process for every request, FastCGI uses the s ame process and

  • 8/10/2019 NIIT_ Solved Answers Bsc

    10/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 10/25

    queues requests to it. It saves lots of memory but it also forces user to wait for the previous requests to finish.

    53. How can you e mbed output of a CGI script in a HTML document? Ans:This can be done using exec directive. For example, following line will print output of addr.cgiYour IP address is:

  • 8/10/2019 NIIT_ Solved Answers Bsc

    11/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 11/25

    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 t he file back t o the client, along with some HTTP response headers.

    61. Explain the importance of Web.xml. Ans.Web.xml is the deployment descriptor on Tomcat server. A deployment descriptor is an XML document that defines all thecomponents of an application along with related information such as initialization parameters and container managed securityconstraints that you want the server to enforce. This file helps the server to k now crucial details about t he application.

    62. Explain how servlet mappings are done in Web.xml. Ans.

    Servlet Mapping is done in Web.xml with the help of the tag as:

    Controller*.do

    graph/graph

    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 t he form http:// localshots:8080/{contextpath}/graph will be mapped tothe graph servlet.

    63. What is a war file? Give its importance. Ans.WAR or Web Application Archive file is packaged servlet Web application. Servlet applications are usually distributed as a WARfiles.

    64. How can you specify session time out in We b.xml? Ans.You can specify session timeout in the attribute of the element. For example, to specify asession timeout of 30 minutes use:30

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

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

    66. How to package an application as WAR file? What are its advantages? Ans:

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

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

    67. How can you specify a custom error page for a particular server error? Ans:This can be done by including following code in Web.xml. Error code is server's internal code. For different error codes, differentpages can be specified. 500 /error.jspWhenever server generates "internal server error" /error.jsp will be displayed.

    68. How to change default server port for Tomcat? Ans:

    Tomcat by default listens on port 8080. Web browsers try to connect to port 80 by default. To change the server port for tomcat editserver.xml file. This file can be found under conf directory of tomc at's inst allation. 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.

    69. What i s a connection pool? List its advantage s. Ans: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.One of the major advantages of configuring a connection pool is that one can change backend without effecting code changes.-------------------------------------------------------------------------------------------------------

    Solutions to Chapter Six Questions70. What i s JSP? How is it is different from CGI programming?

    Ans.JSP is a technology for developing Web pages t hat include dynamic content. A JSP page contains s tandard markup languageelements, such as HTML tags, just like a regular Web page. However, a JSP page also contains special JSP elements that allowthe server to insert dynamic content in the page.CGI is not an efficient solution for developing dynamic Web content. For every request, t he Web server has to create a new

  • 8/10/2019 NIIT_ Solved Answers Bsc

    12/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 12/25

    operating system process, load an interpreter and a script, execute the script and then tear it all down again. This is taxing for theserver 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 codeis directly invoked instead of recompilation. This enables a server to handle JSP pages much faster t han CGI programs.

    71. Write a JSP programming which displays different message to the user based on the time of day. Ans.Time Message 12 && hh < 18 ){message = "Good Afternoon!";}else if( hh > 18 && hh < 21 ){

    message = "Good Evening!";}else{message = "Good Night!";}%>

    72. Explain JSP elements. Ans.JSP elements are of 3 types:n Directive : Specifies information about the page itself that remains the same between requests. For example, it can be used tospecify whether session tracking is required or not, buffering requirements, and the name of t he page that should be used t o reporterrors.n 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 acces s parameters sent with t he request t o lookup a database.n Scripting : Allows you to add small pieces of code in JSP page. These elements are also executed when a page is requested.

    73. What are the advantages of JSP? Ans.The advantages of JSP are:n Supports both scripting and element based dynamic content and allows programmers to develop custom tag libraries to satisfyapplication specific needs.n Are compiled for efficient server processing.n Can be sent in combination with servlets that handle the business logic of the model s upported by Java servlet t emplate engines.n It is specification not a product. Different vendors c an launch and use different implementations of JSP, leading to competition for better quality and performance.n It is an integral part of J2EE, a complete platform for enterprise class applications.

    74. How are JSPs better than Servlets? Ans.Unlike servlets, JSP lets you separate presentation and business logic. You can place the HTML code (presentation) in JSP alongwith some dynamic elements. The business logic remains in the s ervlets or JavaBeans. This approach helps to overcome theproblems with a pure servlet based approach, such as :n Thorough Java programming knowledge is needed to develop and maintain all aspects of the application, since the processingcode and the HTML elements are lumped together.n Changing the look and feel of the application, or adding support for a new type of client, requires the servlet code to be updatedand recompiled.n It is hard to take advantage of Web-page development tools when designing the application interface. If such t ools are used todevelop the Web page layout, the generated HTML must than be manually embedded into servlet code. This process is timeconsuming and error prone.

    75. Explain the various JSP Directives. Ans.JSP directives are JSP elements that provide global information about a JSP page. The various JSP directives are:n page directive : Defines information that will globally affect the JSP containing the directive. The syntax of a page directive is:

  • 8/10/2019 NIIT_ Solved Answers Bsc

    13/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 13/25

    . The various possible attributes are language, extends, import, ses sion, buffer, autoFlush,isThreadSafe, info, errorPage, isErrorPage, and contentType.n include directive : Used to insert text and/or code at the JSP translation time. Its syntax is: . The file attribute can reference a normal HTML file or a JSP file, which must be local to the Web applicationthat contains the directive.n taglib directive : States that the including page uses a custom tag library, uniquely identified by a URO and associated with aprefix that will distinguish each set of custom tags to be used in the page. Its s yntax is: .

    76. Explain JSP error handling. Ans.The JSP architecture provides an error-handling solution t hrough the use of JSPs that are written exclusively to handle JSP errors.The errors that occur most frequently are runtime errors that c an arise either in the body of the JSP page or in s ome 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 andhandled in the body of calling JSP, which signals the end of the error. Exceptions that are not handled in the calling JSP result inforwarding client request, including the uncaught exception, to an error page specified by t he offsending JSP.

    77. Explain implicit objects out, request, and response in a JSP page. Ans.Following are the implicit objects in a JSP page:n out : This implicit object represents a JspWriter that provides a stream back to the requesting client. The most common methodof this object is out.println(),which prints text that will be displayed in the client's browser.n request : This implic it object represents the javax.s ervlet.HttpServletRequest interface. The request object is associated withevery HTTP request. One common use of the request object is to access request parameters. You can do this by calling therequest object's getParameter() method with the parameter name you are seeking. It will return a string with the values matc hing thenamed parameter.n response : This implicit object represents the javax.servlet.HttpServletRequest object. The response object is used to pass databack to the requesting client. A common use of this object is writing HTML output back to the client browser.

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

    Ans:By default JSPs are converted into their corresponding .java files when someone accesses them for the first time. This processinvolves lots of complex parsing and is slow. Precompiling automatically generates corresponding .java files without t he need to visitthe pages.For precompiling under tomcat, use jspc command, under bin directory of tomcat installation as:Jspc -d DIRJ -Webinc PATH_XML -Webapp PATH_JSPWhere, DIRJ is the directory where generated java files will be stored.PATH_XML is an XML file in which servlet mappings will be storedPATH_JSP is the source directory containing JSPs

    79. What i s JSTL? Ans:JSTL or Java Server Pages Standard Tag Library is a freely available collection of custom tags, which provides variousfunctionalities. Some of the tags are: tags to interact with databases; tags to iterate over collections; and tags for internationalization of dates and currencies.

    80. How van you make the browser to reload the page every N number of seconds? Ans:This can be done by adding Refresh header to response. The following JSP code can be used for this:

    81. Which servers have support for JSP? Ans:Weblogic, Resin, Sun Application Server.------------------------------------------------------------------------------------------------------------

    Solutions t o Chapter Seven Questions82. What are servlets? Explain with an example?

    Ans.Servlets are programs that run on a Web server and create Web pages on the fly. To be a servlet, a class should extendHttpServlet and override doGet or doPost or both methods, depending on whether data is sent by GET or POST. These methodstake two arguments, HTTPServletRequest and HttpServletResponse. The HTTPServletRequest has methods that let you find outabout incoming information such as FORM data and HTTP request headers. The HttpServletResponse has method that lets youspecify 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");}}

    83. Explain Servlet life cycle. Ans.

  • 8/10/2019 NIIT_ Solved Answers Bsc

    14/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 14/25

    The lifecyc le of a servlet consists of the following main stages:n Instantiation : The Web server creates an instance of a servlet. This is based on a request or a container startup.n Initialization : The Web server creates the instance's init() method. When the Web server loads a Web application, it also loadsthe initialization parameters associated with the application. This and the previous st ep occur only once during the lifetime of aservlet.n Service : This is the third state in the servlet lifecycle. In this state, the servlet's service() method is called, which generatesresponse. The generation of response involves the following steps:a. Setting t he content t ype of the response. The receiving application (browser) uses t his information to know how to t reat theresponse 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 abstractclass. In the case of servlets, the Web server constructs the Print Writer object from the java.io. OutputStream object associatedwith the underlying connection from the client. With TCP/IP based implementations, Web server usually gets OutputStream objectfrom 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.n Destroy : This is the final stage in a servlet lifecycle. In this stage, the destroy() method is called before shutting down the servlet.

    84. What is the difference between HttpServlet and GenericServlet? Ans.GenericServlet is the base class, which is extended by an abstract class HttpServlet.

    85. What is the difference between doGet() and doPost(). Ans.doGet() needs to be overridden when the data is submitted to the server using the GET method whereas the doPost() method needsto be overridden when POST method is used to submit data to the server.

    86. Explain the relationship between a servlet, its servlet container and the servlet API. Ans. A servlet is a Java program, which runs in a servlet container and is written acc ording to servlet API s pecification. Servlet API is aset of classes and interfaces, which outlines all necessary operations, restrictions, and behaviour for a servlet. A servlet container issoftware, which provides network s ervices over which requests, responses are sent. It s hould provide abstraction in obtaining

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

    87. Which two packages implement the Servlet API? Ans.The two packages are:1. javax.servlet2. javax.servlet.http

    88. Draw a class diagram to show the relationship between major classes in the servlet API. Ans.The class diagram is shown as here:

    Class Diagram

    89. What are the advantages of using servlets to extend server functionality? Ans.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 multit hreading capabilities, which gives it a performance gain.

    90. Describe the request handling cycle and the methods invoked on the servlet by the servlet container. Ans.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 instanceb. Calls the init() method on the above class and passes ServletConfig as parameter

  • 8/10/2019 NIIT_ Solved Answers Bsc

    15/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 15/25

    2. On any further request s ervice() method of s ervlet c lass is c alled and HttpServletRequest and HttpServletResponse are passedas parameters to it.

    91. Which class provides methods of reading the pa ramete rs submitted by a client? Ans.There is no class for this but HttpServletRequest interface provides methods getParameter(), getParameterValues(), andgetParameterMap() for obtaining parameters s ubmitted by client.

    92. Which class provides methods of reading the pa ramete rs specified i n the de ployment descriptor file? Ans.ServletConfig class provides methods getInitParameter() and getInitParameterNames() for reading parameters specified indeployment descriptor.

    93. Which streams are used for sending the contents of the entity-body in the response? Ans.ServletOutputStream is used for sending contents in response, if the data is binary. It extends the OutputStream class. Its object isnormally obtained by calling HttpServletResponse.getOutputStream.For sending character data PrintWriter class is used, which extends the Writer class. Its object is obtained by calling theHttpServletResponse.getWriter() method.

    94. Outline the main steps in implementing the servlet. AnsFollowing are the steps used in implementing a servlet for HTTP communication:1. Import required servlet packages in the c lass.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.

    95. Explain the semantics of the HTML FORM element. Ans.The HTML form element represents a form in which users can input data and submit it to the server for processing. The HTML formtag is as follows:The name attribute specified the name for a form. The action attribute specified the URL of the document or the name of the file towhich the form data is submitted for action and the method attribute specified the HTTP method through which the data is sent tothe server.The action attribute can be a simple st atic Web page or a servlet. The method can be POST or GET.

    A form includes various other elements s uch as tex tbox, lis t, butt ons, or checkboxes.

    96. Which statements are true.1. A web application can have more than web.xml.2. The HTTPServlet class implements the ServletConfig interface.3. The HTTPServlet c lass implements the ServletContext interface4. In a doHttpServletMethodName( ) method, t he request and the response objects can be manipulated in any order.5. The servlet configuration can change from request to request.

    6. The servlet c ontext c an change from request t o request.7. The servlet element must occur before the servlet-mapping in an element in web.xml file.The servlet-class element must specify the full package name of the servlet class.

    Ans:1. False2. True3. False4. True5. False6. False7. True8. True

    FAQ97. How can you w rite me ssages in server log using servlet API? In Tomcat, l ogs are stored in which dire ctory?

    Ans: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" );}catch( Exception e ){ con.log( e ); //will write e.printStackTrace() in log}In Tomcat, logs are stored in logs directory.

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

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

  • 8/10/2019 NIIT_ Solved Answers Bsc

    16/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 16/25

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

    99. How are filters created? List some pra ctical usage of filters. Ans:Filters are created by implementing javax.servlet.Filter interface. Filters are chains, which are linked according to mapping inWeb.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:n Authenticationn Compressionn Parsingn Encoding - Decoding

    101. How to obtain the query string in servlets? Ans:If request type is GET, then name-value pairs are URL encoded and are appended after ? sign in front of the request URL. Querystring or the c ontent after the ? c an be obtained by the request.getQueryString() method.

    -------------------------------------------------------------------------------------------------------Solutions to Chapter Eight Questions

    102. What are the several ways of tracking users? Ans.The several ways in which y ou can track users are:n Using hidden controlsn Using cookien Using sessionsn Using applications

    103. Explain in brief how to use hidden controls in a web page? Give an example. Ans.Using HTML, hidden controls are an easy way to s tore data in a W eb page. You can s tore data in a hidden control and then refer tothe value of control wherever required. Hidden controls are often used when you submit a form to itself. That is if your form's ACTIONattribute is set to the same page which contains the form. In this case, every time the page loads you have to determine whether itis being loaded afresh or after a submission. For this, you can store a text value such as "DONE" in a hidden controlSUBMIT_STATUS, and check for it whenever the page loads. If request.getParameter(SUBMIT_STATUS) returns a NULL value, itmeans that the form is being loaded afresh.This logic is demonstrated in the following code:Enter your name:

  • 8/10/2019 NIIT_ Solved Answers Bsc

    17/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 17/25

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

    107. List down a ny 6 me thods of HttpServletResponse class and their functionality. Ans.Following are the methods of the HttpServletResponse class :n int SC_ACCEPTED : Indicates that a request was accepted for processing but was not completedn int SC_BAD_GATEWAY : Indicates that the HTTP server received an invalid response from a server, when acting as a proxy or gatewayn int SC_BAD_REQUEST : Indicates that the request sent by the client was incorrectn int SC_CONFLICT : Indicates that the request cannot be completed because of a conflict with the current state of the resourcen int SC_CONTINUE : Indicates that the client can continue

    108. Explain in brief how to create a cookie with an example. Ans.You can create a cookie by instantiating an object of the Cookie class. For example, to create a cookie name 'mycookie', with thevalue 'this is the cookie value', you can use the following code snippet:Cookie mycookie = new Cookie("mycookie", "t his is the cookie value");mycookie.setMaxAge(24*60*60);respone.addCookie(mycookie)//install c ookie on browser The setMaxAge() method sets the time after which the cookie will expire. The response.addCooki() method will install the cookie onthe browser.

    109. Explain in brief how to read a cookie with an example. Ans.You can read a cookie as:Cookie[] cookies = request.getCookies();for(int i=0;i

  • 8/10/2019 NIIT_ Solved Answers Bsc

    18/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 18/25

    particular session. Timeout setting in web.xml is universal. By using the above function call timeouts can be set according to user role.

    115. What is SOAP call? What is its major advantage? Ans: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.

    116. What is Locale? How can you obtain client's Locale in using servlet API? Ans:Locale is t he user's top preference for language stored in t he browser. This information can be crucial for some web applications.For example, using this information, web application can provide interface elements in c lient's preferred language that is, it c anbehave like an automated multilingual software.

    Using servlet API, Locale information can be obtained as an object of java.util.Locale. For t his, c allLocale locale = request.getLocale()To obtain the preferred language, call locale.getDisplayLanguage().

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

    Ans:Yes, if a servlet has ended prematurely with an exception thrown, filter can be put in to process it. Such filter can obtain thrownexception and error code by usingThrowable throwable = (Throwable)request.getAttribute("javax.servlet.error.exception");Integer status_code = ((Integer)request.getAtt ribute("javax.servlet.error.status_code"));.

    118. Explain a practical use of redirecting. How can you redirect a client using servlet API? Ans:Redirecting is used in many phases of web application, logout module is one such phase. Here, all session information isinvalidated, database connections are released, and client is t hen redirected to application's home page. To redirect a user usingservlet, API uses:

    response.sendRedirect( page_url_to_redirect );Redirection c auses client to send a request for the page specified as input in above call.--------------------------------------------------------------------------------------------------------

    Solutions to Chapter Nine Questions119. What is SSL? Why do you require SSL?

    Ans.SSL or Secure Socket Layer is a protocol that authenticates Web sit es to browsers. It is also used for encrypting communicationbetween browser and Web servers. To enable SSL, you simply need to install digital certificates or Server ID.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.

    120. Explain SSL working. Ans.SSL has two distinct entities, server and client. The client is the entity that initiates the transaction whereas the server is the entitythat responds to the client and negotiates which cipher suites are used for encryption. In SSL, the Web browser is the client andthe Web s ite server is the s erver. Three protocols lie within SSL, the Handshake protocol, the Record protocol, and the Alertprotocol. The client authenticates the server during the Handshake protocol. When the s ession 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.

    121. What is XML? Explain in brief. Ans.XML is a simple, common format for representing structured information as text. You can create your own tags to define andstructure data, and transmit it. The basic syntax of XML is ext remely simple. As with HTML, XML represents information as textusing 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. Elementscan contain other elements but they must be properly nested. Elements can also contain text or a combination of elements andtext.

    122. Given an ove rview about EJBs. Ans.Enterprise Java Beans (EJB) is a server-side component that execut es specific business logic on a server when invoked by a localor remote client. EJB is actually a framework for writing distributed programs. It involves a s tandardization agreement that enables a

    component to run within any application s erver. The agreement is accomplished by implementing a set of Java interfaces from theEJB API. Note that EJBs are not GUI components.

    123. What a re the advantage s and disadvantages of EJBs. Ans.Following are the advantages of EJBs:n Many vendor application servers c onform to the J2EE specification allowing you to select a best-of-breed solution.n To handle fluctuations in resource demand server-side resources can easily be scaled by adding or removing servers.n Application servers provide access to complex s ervices, such as transaction and security management, resource pooling, JNDI(Java Naming and Directory Interface), and component lifecycle management.Following are the disadvantages of EJBs:n EJB has a large and complicated specification.n EJBs take time to develop. Also, they are difficult to debug. Occasionally, the bug may not be in your code but in the applicationserver itself.n Frequently released newer versions of E JB specifications render application obsolete quick ly.

    124. Explain e ntity beans and session bea ns?

  • 8/10/2019 NIIT_ Solved Answers Bsc

    19/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 19/25

    Ans. An entity bean is an object with the following special properties:n It is permanent. It does not get destroyed itself after a program finishes executing.n It is network-based. It can be used by any program over a network provided the program is able to access the bean on thenetworked machine.n 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 t he method returns from the server, t he threadresumes execution.n It is identified by a primary key. Entity beans must have a primary key. The primary key is unique - each entity bean is uniquelyidentified by its primary key. For example, an employee entity bean may have Social Security number as primary key. You canonly 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 itis 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 alsodo not have a primary key. Unlike entity beans, session beans are not primarily meant to be shared or found later.

    125. Briefly describe the remote and home interfaces in EJBs? Ans. A remote interface is t he business end of EJB. It is the set of s ervices 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 instanceof an EJB. The methods used to find existing EJBs are shown as finder methods. Since session beans are not designed to beshareable, there are no session bean finder methods.

    126. What is DTD? Ans.DTD or Document Type Definitions is a document that contains grammar rules for validating an XML document. It is a schemaspecification method for XML.

    FAQ127. What is JNDI?

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

    128. What is XSLT? Ans:XSLT or Extensible St ylesheet Language Transformation is used to convert either one xml document into another (such as asubset) or t o convert xm l data into presentable HTML page.

    129. What is HTTPS? On which port it w orks by default? Ans:HTTPS is HTTP + SSL. It is the secured communication channel that works by the rules of HTTP. By default it works on port 443.

    130. What is EAR file? Ans:EAR or Enterprise Archive is a J2EE file format that contains various components such as beans into an easy to deploy andcompressed format.

    131. What is a data island? Ans:It is XML embedded inside HTML. They are used to store client side information and are used as a better alternative for hidden tags.------------------------------------------------------------------------------------------------------------

    132. Write an example HTML page containing a table 4 X 3 and each row coloreddifferently.

    Ans. The following is an HTML page containing a table 4 X 3 and each row colored differently:Colored Table

  • 8/10/2019 NIIT_ Solved Answers Bsc

    20/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 20/25

    133. Write a n HTML program to demonstrate tex t characteristics tags.

    Ans. The following code demonstrates some of the important t ext characteristics t ags in HTML:Text Characteristics

    Text Characteristics inHTML

    HTML is a formatting language for Web pages. Below is an example of HTML code




    & followed by gt represents the greater than sign.134. Create a simple HTML page to demonstrate usage of anchor tags.

    Ans. The following HTML page, demonstrates the usage of anchor tags:Anchor Tag CharacteristicsAll in One

    In section 1 you can search. In section 2 you can shop.

    Section 1:

    Search on Google

    Search on Yahoo

    Section 2:

    Shop on ebay

    Download wallpapers

    Order Custom T-ShirtsNews

    135. Explain the uses of script tags.

    Ans. The script tag marks t he beginning and end of JavaScript in a web page. You can specify the scripting language in the scripttags' 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:136. What is the difference between HTML and DHTML?

    Ans. HTML is a markup language used to create stat ic web pages. DHTML on the other hand is not a language by itself but acombination of different technologies such as HTML, CSS, JavaScript, and DOM. It is used to create dynamic pages.137. Give difference between JavaScript and CGI programming.

    Ans. JavaScript is a s cripting language whereas CGI itself is a standard, which uses various other programming languages.JavaScript is used mainly on t he client s ide whereas CGI programming is used to implement server side sc ripting. In addition,JavaScript is embedded in HTML documents whereas CGI programs reside in their own independent files.138. Explain PERL control structures with appropria te ex amples.

    Ans. P ERL control structures inc lude: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";

  • 8/10/2019 NIIT_ Solved Answers Bsc

    21/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 21/25

    }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){ $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 usingforeach 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 loopinitializer, the loop condition, and the loop reinitializer. For example, to perform an action such as printing use thefor loop as:

    for($i=0;$iheader;print $cgi->start_html( "Question Nine" );$text = $cgi->param( 'text' ); if( $text ) { print "You entered $text"; } else { print '';

  • 8/10/2019 NIIT_ Solved Answers Bsc

    22/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 22/25

    print '
    '; print '
    ';

    print "";

    }print $cgi->end_html;141. Write a CGI application that accepts 3 numbers from the users and displays the LCM of three numbers using GETand POST methods.

    Ans. #!/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 ''; print 'Enter First Number
    '; print 'Enter Second Number
    '; print 'Enter Third Number
    ';

    print '
    ';print "";

    }

    print $cgi->end_html;sub findLCM(){ 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;142. Explain the role of Deployme nt descriptors.

    Ans. A deployment descriptor is an XML document t hat defines all the components of an application along with related informationsuch as initialization parameters and container managed security constraints that you want the server to enforce. This file helps theserver to know crucial details about t he application.143. Explain the importance of Web.xml.

    Ans. W eb.xml is the deployment descriptor on Tomcat s erver. Same as que 3 above.144. Explain how servlet mappings are done in Web.xml.

    Ans. S ervlet Mapping is done in Web.xml with the help of the tag as:

    Controller*.do

    graph/graph

    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 t he form http:// localshots:8080/{contextpath}/graph will be mapped tothe graph servlet.145. What is a war file? Give its importance.

    Ans. W AR or Web Application Archive file is packaged servlet Web application. Servlet applications are usually distributed as aWAR files.

    146. How can you specify session time out in Web.xml?Ans . You can specify session timeout in the attribute of the element. For example, to specifya session timeout of 30 minutes use:30

  • 8/10/2019 NIIT_ Solved Answers Bsc

    23/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    http://sslifehacker.blogspot.in/search/label/solved%20Answers%20Bsc.IT%20-52 23/25

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

    Ans. A servlet is a Java program, which runs in a s ervlet container and is written according to servlet API specification. Servlet APIis a set of classes and interfaces, which outlines all necessary operations, restrictions, and behaviour for a servlet. A servletcontainer is software, which provides network s ervices over which requests, responses are sent. It s hould provide abstraction i nobtaining requests and formatting responses and at least support communication over HTTP. For example, Tomcat is a servletcontainer.148. Draw a class diagram to show the relationship between major classes in the servlet API.

    Ans. The class diagram is shown as here:

    1

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

    Ans. Following are the advantages of using servlets:1. It helps to achieve platform independence.2. It provides performance improvement as c lasses 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 multit hreading capabilities, which gives it a performance gain.

    150. Describe the request handling cycle and the methods invoked on the servlet by the servlet container. Ans. Following are the operations done on a servlet by s ervlet 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 instanceb. 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 andHttpServletResponse are passed as parameters to it.

    151. Which class provides methods of reading the pa ramete rs submitted by a client?

    Ans. There is no class for this but HttpServletRequest interface provides methods getParameter(), getParameterValues(), andgetParameterMap() for obtaining parameters s ubmitted by client.152. Which class provides methods of reading the pa ramete rs specified i n the de ployment descriptor file?

    Ans. S ervletConfig class provides methods getInitParameter() and getInitParameterNames() for reading parameters specified indeployment descriptor.153. Which streams are used for sending the contents of the e ntity-body in the response?

    Ans. S ervletOutputStream is used for sending contents in response, i f the data is binary. It extends the OutputStream c lass. Itsobject 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 theHttpServletResponse.getWriter() method.154. Outline the main steps in implementing the servlet.

    Ans Following are the steps used in implementing a servlet for HTTP communication:1. Import required servlet packages in the clas s.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.

    155. Explain the semantics of the HTML FORM ele ment. Ans. The HTML form element represents a form in which users c an input data and submit it t o the server for processing. The HTMLform tag is as follows:The name attribute specified the name for a form. The action attribute specified the URL of the document or the name of the file towhich the form data is submitted for action and the method attribute specified the HTTP method through which the data is sent tothe server.The action attribute can be a simple st atic Web page or a servlet. The method can be POST or GET.

    A form includes various other elements s uch as tex tbox, lis t, butt ons, or checkboxes.156. Explain in brief how to use hidden controls in a web page? Give an example.

    Ans. Us ing HTML, hidden controls are an easy way to s tore data in a Web page. You can s tore data in a hidden control and thenrefer 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 s et to t he same page which contains the form. In this c ase, every time the page loads you have to determinewhether it is being loaded afresh or after a submission. For this, you can store a text value such as "DONE" in a hidden controlSUBMIT_STATUS, and check for it whenever the page loads. If request.getParameter(SUBMIT_STATUS) returns a NULL value, itmeans that the form is being loaded afresh.This logic is demonstrated in the following code:

  • 8/10/2019 NIIT_ Solved Answers Bsc

    24/25

  • 8/10/2019 NIIT_ Solved Answers Bsc

    25/25

    8/21/2014 NIIT: solved Answers Bsc.IT -52

    All Comments

    Satyendra Sharma

    10 have me in circles

    Add to circles

    Google+ Followers

    Copyright 2013 Created By - Satyendra Sharma. Simple template. Powered by Blogger .

    Assignments (3) Cracking Password (2) Downloads (2) ibps (2) Icons Pack (2) PRACTICAL

    Labels

    http://sslifehacker.blogspot.in/search/label/PRACTICALhttp://sslifehacker.blogspot.in/search/label/Icons%20Packhttp://sslifehacker.blogspot.in/search/label/ibpshttp://sslifehacker.blogspot.in/search/label/Downloadshttp://sslifehacker.blogspot.in/search/label/Cracking%20Passwordhttp://sslifehacker.blogspot.in/search/label/Assignmentshttp://www.blogger.com/https://plus.google.com/105262405286077301848https://plus.google.com/102066855548888917959https://plus.google.com/111199550385521280450https://plus.google.com/109931362660505788545https://plus.google.com/112354499610531326094https://plus.google.com/114700096026733923382https://plus.google.com/105221740964368678996https://plus.google.com/104293862079951853374https://plus.google.com/+PreetyUzlainsarkariNaukrihttps://plus.google.com/109931362660505788545