Posts Tagged ‘JSP FAQ’

JAVASCRIPT FAQ

Wednesday, March 25th, 2009

 

 

This FAQ has been taken from http://www.intranetjournal.com/faq/js-faq.shtml with the permission of the editor.

For more details visit Intranet Journal at

http://idm.internet.com/index.html

http://www.intranetjournal.com/faq/js-faq.shtml

 

1.    General

1.      What is JavaScript?

2.      What versions of the language does this FAQ cover?

3.      What’s not covered here?

4.      Who wrote this FAQ?

5.      Can I mirror or reprint this FAQ?

 

2.    JavaScript Documentation

1.      Where can I find online documentation for JavaScript?

2.      Where is the official bug list for JavaScript?

3.      Read any good JavaScript books lately?

 

3.    First Principles

1.      What are the language’s basic entities?

2.      How does JavaScript model the world? (Nifty Object Map.)

3.      What are JavaScript event handlers?

4.      How is JavaScript syntax like C / C++?

 

4.    How do I …

1.      … embed JavaScript in a web page?

2.      … use ‘var’ to make a variable name local?

3.      … use quotation marks when scripting?

4.      … submit forms by e-mail?

5.      … script a visit counter?

6.      … script a calendar on the fly?

7.      … access objects and scripts in windows opened with window.open()?

8.      … use JavaScript to password-protect my Web site?

9.      … write browser-independent scripts?

10. … match text patterns like I can in Perl?

11. … prevent others from seeing/copying my scripts?

12. … detect whether JavaScript support has been disabled?

 

5.    Troubleshooting

1.      What can’t JavaScript do?

2.      Where can scripts go wrong?

3.      What are the most common scripting mistakes?

4.      Why won’t my script work …

5.      Jscript issues

6.      Portability

 

6.    Programming Tools

1.      What tools are available for developing JavaScript pages?

1.      NetObjects ScriptBuilderTM

2.      Borland IntraBuilderTM

3.      Netscape Visual JavaScript 1.0

2.      Are there any debugging tools for JavaScript?

 

7.    Other Sources

 

General

1. What is JavaScript?

JavaScript is a platform-independent, event-driven, interpreted programming language developed by Netscape Communications Corp. and Sun Microsystems. Originally called LiveScript (and still called LiveWireTM by Netscape in its compiled, server-side incarnation), JavaScript is affiliated with Sun’s object-oriented programming language JavaTM primarily as a marketing convenience. They interoperate well but are technically, functionally and behaviorally very different.

JavaScript is useful for adding interactivity to the World Wide Web because scripts can be embedded in HTML files (i.e., web pages) simply by enclosing code in a <SCRIPT> </SCRIPT> tag pair. All modern browsers can interpret JavaScript — albeit with some irritating caveats. (More about them below.)

In practice, JavaScript is a fairly universal extension to HTML that can enhance the user experience through event handling and client-side execution, while extending a web developer’s control over the client’s browser. And that’s worth a FAQ.

                                                                                                            BACK TO TOP

2. What versions of the language does this FAQ cover?

This FAQ covers the language through JavaScript 1.2, the version deployed in Netscape Communicator 4.0x, plus some compatibility items with Jscript as implemented in Microsoft Internet Explorer 3.0x. The focus here is on client-side JavaScript.

                                                                                                            BACK TO TOP

3. What’s not covered here?

Other browser-based scripting languages such as Microsoft VBScript. Server-side JavaScript and Netscape LiveWire Pro. Database connectivity. Known bugs. Netscape’s JSRef source libraries for embedding the JavaScript interpreter in third-party code.

                                                                                                            BACK TO TOP

4. Who wrote this FAQ?

The answers herein have been compiled from several sources. The largest contribution is from Danny Goodman’s JavaScript Mini-FAQ, updated periodically in the newsgroup comp.lang.javascript. Postings to that newsgroup are also a rich source of questions and answers. Items quoted or paraphrased from books on the subject are attributed in the text. Finally, we at IDM have added our own two cents worth.

                                                                                                            BACK TO TOP

5. Can I mirror or reprint this FAQ?

Yes, with two restrictions. You must retain the previous paragraph (”Who wrote this FAQ?”), and you must cite Intranet Journal, giving the URL in print media and/or linking idm.internet.com in online media.

                                                                                                            BACK TO TOP

JavaScript Documentation

1. Where can I find online documentation for JavaScript?

ECMAScript (ECMA-262) has since June 1997 been the official scripting standard for the Web. It is documented at:
http://www.ecma.ch/stand/ecma-262.htm

Current JavaScript docs (for Netscape) are available at:
home.netscape.com/eng/mozilla/3.0/handbook/javascript

Netscape’s JavaScript FAQ is at:
developer.netscape.com/support/faqs/champions/javascript.html

A zipped set of Netscape’s HTML documents is available at:
developer.netscape.com/library/documentation/jshtm.zip

Microsoft’s scripting language site is:
http://msdn.microsoft.com/scripting/

                                                                                                            BACK TO TOP

2. Where is the official bug list for JavaScript?

Netscape maintains a page of JavaScript Known Bugs in its online Navigator Release Notes. Unfortunately, according to guru Danny Goodman, “this list is not complete,” and we know of no definitive, well-maintained alternative.

                                                                                                            BACK TO TOP

3. Read any good JavaScript books lately?

Yes! As with computer books generally, texts on browser scripting are plentiful, but the number of good ones is surprisingly small. Nor are the best ones always the most visible. Intranet Journal’s favorites, for instance, include a pair of texts from British publisher Wrox Press Ltd.:

  1.  

These programmer’s references are so good because they work from the browser object model up, recognizing fundamental differences between the Microsoft and Netscape approaches. As the titles suggest, they treat the gamut of client-side techniques for making web pages dynamic: JavaScript, VBScript, Layers and Style Sheets. They excel as references for each.

The Wrox books are written for a programming audience. Also in this category, but with different emphases, are the following:

  1.  
    • Dynamic HTML: The Definitive Reference (O’Reilly, July 1998) by Danny Goodman. A compendium for Web content developers that contains reference material for all of the HTML tags, CSS style attributes, browser document objects, and JavaScript objects.
    • Netscape ONE Developer’s Guide (Sams Publishing, April 1997) by William Robert Stanek & Blake Benet Hall. This programmer’s guide to developing commercial-grade Web sites for the Netscape 2.x environment covers client- and server-side scripting in detail.
    • JavaScript: The Definitive Guide (O’Reilly, June 1998), by David Flanagan. One of O’Reilly’s Nutshell Handbooks, this guide furthers a tradition that includes Larry Wall’s Programming Perl and definitive texts on every Unix utility. But why a rhino?

Beginners and less technical webmasters may find one of the following sources a more suitable introduction to scripting.

  1.  
    • Practical Javascript Programming (M&T Books, March 1997), by Reaz Hoque. Contains extensive plug & play code samples, plus an introduction to Netscape’s server-side language, LiveWire Pro.
    • JavaScript Bible, 3rd Ed. (IDG Books, March 1998), by Danny Goodman.
    • JavaScript Sourcebook (John Wiley & Sons, Aug 1996), by Gordon McComb.
    • Programming JavaScript for Netscape 2.0 (New Riders, 1996), by Tim Ritchey. Older, rich in background, emphasizes JavaScript as stepping stone to Java.

                                                                                                            BACK TO TOP

First Principles

1. What are the language’s basic entities?

A. As in most object-oriented, event-driven programming languages, there are four distinct entities in JavaScript:

  • OBJECTS. A discussion of objects is beyond the scope of this FAQ (see the section “Objects and the Web” in Intranet Journal’s Intranet FAQ for background). It’s impossible to understand JavaScript without knowing the following essentials, however:
    1. everything you can control in a web browser is an object comprising properties and methods (sometimes referred to in the literature as attributes and operations, respectively)
    2. properties define the state of an object; e.g., red text, 10-element array
    3. methods define the actions that change the state of an object; e.g., fontcolor("red") sets the color of a text object to red.
  • FUNCTIONS. Methods that operate outside of objects; e.g., escape() and unescape(), JavaScript functions that perform ASCII to hex conversions. The existence of non-object-specific functions in JavaScript keeps it from being a truly object-oriented language like Java.
  • STATEMENTS. Programming commands that control object lifecycles and the flow of execution; e.g., if..else, while. JavaScript statements and syntax closely resemble those of the ‘C’ programming language.
  • EVENTS. Things that happen, usually as a result of user actions, to which a JavaScript program can respond; e.g., a mouse click. Events always happen in relation to a given object, such as a button in a form (for which onClick is a typical event), or an entire web page (sample event: onLoad). The code that specifies what the object should do in response to an event is a special type of method called an event handler.

                                                                                                            BACK TO TOP

2. How does JavaScript model the world?

A. This question goes to the heart of any OOPS [Object-Oriented Programming System]. The abbreviated answer given here — lengthy as it is — omits important differences between the Netscape and Microsoft browser object models, and between various versions of JavaScript. For a more accurate discussion refer to one of the programmer’s references cited elsewhere in this FAQ.

                                                                                                            BACK TO TOP

3. What are JavaScript event handlers?

A. Among other things, event handlers are the subject of part II of Intranet Journal’s 3-part tutorial, JavaScript 101, by Reaz Hoque. That’s a good starting place. Also refer to the following diagram from Wrox Press Ltd., which puts browser events and the code that handles them in context.

Handling Browser Events

 

 

                                                                                                            BACK TO TOP

4. How is JavaScript syntax like C / C++?

A. The languages have enough in common to make learning one easy if you know the other. By the same token, the differences are subtle enough to trip up those proficient in both. Here’s a short list comparing C and JavaScript:

  • Terminating JavaScript command lines in semicolons is optional; in C it’s mandatory. Recommended practice is to use them religiously in both languages (and Java as well).
  • Both JavaScript and C are case-sensitive; ‘doThis’ is different from ‘DOTHIS’. Experienced programmers learn to love this feature, which drives beginners nuts.
  • Both JavaScript and C are block-structured computer languages and employ curly brackets — ‘{’ and ‘}’ — to delimit blocks.
  • Both JavaScript and C employ quotation — enclosure in single or double quote marks — to designate text strings.
  • Arrays in both JavaScript and C are zero-based; the first element is myArray[0], not myArray[1].
  • Both JavaScript and C employ ‘==’ for comparison, ‘=’ for equality, and ‘!’ for negation. In fact the set of JavaScript operators is essentially borrowed from C (right down to the deprecated ternary construct a ? b : c).
  • Both JavaScript and C employ the symbols /* to designate a comment */. JavaScript also permits the use of ‘//’ for short comments, as in C++.

Finally, JavaScript’s statements are a strict subset of C++’s, offering a smaller selection of identical looping and conditional constructs.

                                                                                                            BACK TO TOP

How do I …

… embed JavaScript in a web page?

Tim Ritchey offers a number of useful style guidelines in his book Programming JavaScript for NetscapeTM 2.0. Here’s how he writes JavaScript:

<SCRIPT LANGUAGE="JavaScript">
<!-- hide script from older browsers
 
     [insert your code here]
 
// end script hiding -->
</SCRIPT>

Ritchey also points out that JavaScript accepts the C-language comment delimiters /* comment */, useful for multi-line comments.

                                                                                                            BACK TO TOP

… use the same variable name several times in a script?

By default all variables in JavaScript are global, meaning they retain their values everywhere in a scripted web page. To make a variable local to a block (such as a function), declare it with the keyword var. Here’s a n example:

// here 'i' is a global counter variable that could, if reused
// elsewhere in this script, create hard-to-find errors
 
for( i=1; i<=N; i++ ) {
     [code to iterate]
}
 
// to ensure that 'i' exists only in the scope of this
// counter, use var:
 
for( var i=1; i<=N; i++ ) {
     [ ... ]
}

Limiting a variable's scope is especially valuable when cutting-and-pasting an existing script, not necessarily written by you, into a new web page. If you use local variables in your functions, you needn't worry about stepping on variables in t he reused code.

                                                                                                            BACK TO TOP

... use quotation marks when scripting?

There are two types of quote mark in JavaScript, the single-quote (') and double-quote ("). Either can be used to delimit a string literal, or sequence of characters. For example:

myDblQString = "This string is surrounded by double-quote marks.";
mySngQString = 'This string is surrounded by single-quote marks.';

However, since HTML itself makes extensive use of double-quotes within tags, it's a good idea to use single-quotes to set off strings in your scripts. This is particularly useful when your code contains quoted elements, as follows:

onClick = "alert( 'Are you sure?' )";

Strings containing apostrophes, which are identical to single-quotes, require you to use the backslash character (\) to escape the apostrophes, as shown below:

myEscString = 'John didn\'t like Mary\'s hat.';

Quoted strings can be combined with other strings, whether literals or variables:

errMsg = "Passwords are case-sensitive.";
message = "Error: " + errMsg;
// assigns 'Error: Passwords are case-sensitive.' to message

 

 

                                                                                                            BACK TO TOP

... submit forms by e-mail?

The most reliable way is to use straight HTML via a Submit style button. Set the ACTION of the <FORM> to a mailto: URL and the ENCTYPE attribute to "text/plain". For security reasons, the form.submit() method does not submit a form whose ACT ION is a mailto: URL.

Microsoft Internet Explorer 3.0x does not e-mail forms directly, though it can launch an e-mail client such as Eudora Pro or Outlook Express. These in turn convey identifying info to the recipient, offering a measure of security.

                                                                                                            BACK TO TOP

... script a visit counter?

At best, a client-side script can show the visitor how many she has been to the site (storing the count in a local cookie). A count of total hits to the server requires a server-side program.

                                                                                                            BACK TO TOP

... script a calendar on the fly?

If you view the source of Intranet Journal's Events page, you'll have your answer in freely distributable form. Features of this homegrown implementation include:

object-oriented, with perpetual calendar class

reusable isLeapYear() function

highlights current day

Y2000 compliant

easily invoked from page <BODY> via forms or embedded script commands. Here's a typical invocation:

<SCRIPT LANGUAGE="JavaScript">
<!--
//  insert on-the-fly day calendar
  makeCal(9, 1997);  // September 1997
// -->
</SCRIPT>

To use the code, you'll need to change the part of the getHTML() method demarked "page specific stuff." The code is unsupported and not warranted for any particular use.

                                                                                                            BACK TO TOP

... access objects and scripts in the window I open with window.open()?

First, be sure to assign an 'opener' property to the new window if you are using a version of JS that doesn't do it automatically (Navigator 3.0x and MSIE 3.0x do it automatically). The following script should be a part of every new window creation:

   var newWind = window.open("xxx","xxx","xxx")  // u fill in blanks
   if (newWind.opener == null) {  // for Nav 2.0x
      newWind.opener = self  // this creates and sets a new property
   }

To access items in the new window from the original window, the 'newWind' variable must not be damaged (by unloading), because it contains the only reference to the other window you can use (the name you assign as the second parameter of open() is not valid for scripted window references; only for TARGET attributes).< /P>

To access a form element property in the new window, use:

   newWind.document.formName.elementName.property

From the new window, the 'opener' property is a reference to the original window (or frame, if the window.open() call was made from a frame). To reference a form element in the original window:

   opener.document.formName.elementName.property

Finally, if the new window was opened from one frame in the main browser window, and a script in the new window needs access to another frame in the main browser window, use:

   opener.parent.otherFrameName.document.formName

 

                                                                                                            BACK TO TOP

... use JavaScript to password-protect my Web site?

There are a number of schemes, but be warned that most fail to deflect the knowledgeable script programmer because no matter how you encode the correct password (e.g., bit shifting), both the encoding algorithms and the result have to be in the script -- whose source code is easily accessible. If you're only interested in keeping out casual visitors, this method may suffice.

A more secure way is to set the password to be the name or pathname of the HTML file on your site that is the 'true' starting page. Set the location to the value entered into the field (unfortunately, you cannot extract the value property of a password object in Navigator 2.0x). Entry of a bogus password yields an 'invalid URL' error.

If the protected pages need additional security (e.g., an infidel has managed to get the complete URL), you might also consider setting a temporary cookie on the password page; then test for the existence of that cookie upon entry to every protected page, and throw the infidel back to the password page.

                                                                                                            BACK TO TOP

... write browser-independent scripts?

Strictly speaking, you can’t. Many browsers don't support Javascript at all. We’ve come to think of the Web as a franchise fought over by Netscape and Microsoft, but there are still people who browse with Lynx, NCSA Mosaic, UdiWWW, Cello – well, maybe not Cello. ;^)

Speaking informally, there are two ways to write more portable code. One is to use only least-common-denominator features supported by all versions of Navigator and MSIE. We’re talking JavaScript 1.0, introduced with Netscape 2.0 and IE 3.0. This approach has a couple of drawbacks:

  • you lose many of the desirable features available in more recent versions
  • the behavior of various browsers differs even at this primitive level, and there are some bugs in JavaScript 1.0.

Your other option is browser-detection. By running a script at load time that identifies the browser it’s executing in, you can branch conditionally to appropriately optimized code. This is good stuff, though it won’t work for all browsers and requires you to add a lot of gobbledy-gook to your web pages.

Here’s a typical browser-detection routine you can customize:

<SCRIPT language="JavaScript">
<!--
function checkBrowser(NSvers,NSpass,NSnoPass,IEvers,IEpass,
                      IEnoPass,OBpass,URL,altURL) {
  var newURL = '', version = parseFloat(navigator.appVersion);
  if (navigator.appName.indexOf('Netscape') != -1) {
    if (version >= NSvers)
       {if (NSpass>0) newURL = (NSpass==1)?URL:altURL;}
    else
       {if (NSnoPass>0) newURL = (NSnoPass==1)?URL:altURL;}
  } else if (navigator.appName.indexOf('Microsoft') != -1) {
    if (version >= IEvers)
       {if (IEpass>0) newURL = (IEpass==1)?URL:altURL;}
    else
       {if (IEnoPass>0) newURL = (IEnoPass==1)?URL:altURL;}
  } else if (OBpass>0) {newURL = (OBpass==1)?URL:altURL};
 
  if (newURL) {
    window.location = unescape(newURL);
    document.returnValue = false;
  }
}
//-->
</SCRIPT>

This code, which should appear in the HEAD section of a web page, jumps to another page if the visitor is using a browser earlier than version 4.0.

                                                                                                            BACK TO TOP

... match text patterns like I can in Perl?

The short answer is, "By forgetting about JavaScript and coding server-side CGI scripts in Perl."

A longer, browser-dependent answer: read Angus Young's article, "String matching and replacing in JavaScript 1.2."

                                                                                                            BACK TO TOP

... prevent others from seeing/copying my scripts?

You can't. There is no way to produce an HTML document that can be rendered in a browser but whose source cannot be examined in its entirety, scripts included. And since web browsers have functions like "View Source" and "Save As HTML," copying is a cut-and-paste operation.

Putting a copyright notice at the head of your code affords some legal protection.

Microsoft has introduced a technique called script encoding that garbles HTML, ASP, VBS, and JScript source code so that it is unreadable by a casual user. (The lightweight encryption used won't stop determined hackers.) The technique requires Microsoft's version 5.0 Script Engine; it won't execute in Netscape Navigator or earlier MSIE versions.

                                                                                                            BACK TO TOP

... detect whether JavaScript support has been disabled?

Common sense says that if you're going to detect if JavaScript is disabled, you'd better do it in something besides JavaScript! Check instead to see if scripting is enabled.

You might, for instance, use something like document.location = 'java_page.html' to redirect the browser to a new, script-laden page. Failure to redirect implies that JavaScript is unavailable, in which case you can either resort to CGI routines or insert appropriate code between the <NOSCRIPT> tags. (NOTE: NOSCRIPT is only available in Netscape Navigator 3.0 and up.)

                                                                                                            BACK TO TOP

Troubleshooting

1. What can't JavaScript do?

Quite a bit. Primarily for security reasons, client-side scripting languages like JavaScript cannot:

  • read or write random text files on the local disk or on the server
  • invoke automatic printing of the current document
  • control browser e-mail, news reader, or bookmark windows and menus
  • access or modify browser preferences settings
  • capture a visitor's e-mail address or IP address
  • quietly send me an e-mail when a visitor loads my page
  • launch client processes (e.g.,Unix sendmail,Win apps,Mac scripts)
  • capture individual keystrokes
  • change a document's background .gif after the page has loaded
  • change the current browser window size, location, or options
  • get rid of that dumb "JavaScript Alert:" line in alert dialogs

Many of these items are possible in Netscape Communicator 4.0, which features the enhanced (and proprietary) version 1.2 of JavaScript. Moreover, those items perceived to be security risks (e.g., access browser settings) require "signed JavaScript."

MSIE JScript v2 (more below) can read/write local files via ActiveX - a source of that architecture's widely publicized security pitfalls.

                                                                                                            BACK TO TOP

2. Where can scripts go wrong?

There are three distinct areas where errors can occur in any computer program:

  • Load-time errors
  • Run-time errors
  • Logic errors

Load-time errors
Your script is part of a web page. When someone browses (i.e., requests) that page, your server returns it over the network. On receiving it the requesting browser loads your page: HTML, JavaScript, and any other objects it contains.

Load-time errors are caught by the JavaScript interpreter. As the browser loads your script, it performs myriad checks for basic language problems -- usually syntax errors. If, for instance, you leave off the closing half of a pair of parentheses, the interpreter will tell you about it in the form of a load-time error. Why? Because a script can't run until it has loaded successfully.

By checking your scripts in two browsers -- Netscape Navigator 3.0 (or later) and Microsoft Internet Explorer 3.0 (or later) -- you leverage the language-checking abilities of JavaScript itself to detect load-time errors.

Run-time errors
If your script loads, it will run. It may perform exactly as you designed it to, or it may crash and burn. Like load-time errors, problems at run-time are detected and reported by the JavaScript interpreter. In effect, it says (very quietly): "I loaded that nice-looking script and now it's breaking the rules, corrupting memory and whatnot. I'd better tell somebody." Up pops an alert window to apprise you of the run-time error.

When a program is running it manipulates stored data, operating on values in memory as specified by program commands. Thus, whereas errors occur at load time chiefly due to bad syntax, run-time errors are often due to misuse of the language's commands.

For instance, you'll get a run-time error if at some point your script divides by zero (illegal in any language).

Logic errors
These are the bad guys, problems worthy of the epithet "bugs." Errors loading or running your script are caught by the machine; errors in the logic of you program can only be caught by you or your users -- in other words, humans. When your script runs without complaining but ends up doing the wrong thing, you've got a logic error.

The best way to verify your program logically is to stress it. You probably won't be able to exercise all the possible inputs, outputs, if-then statements and loops, but by hitting a few major ones, you gain confidence that any errors are at least well hidden. If and when these occur, of course, they may be equally hard to trace. But that's software for you.

                                                                                                            BACK TO TOP

3. What are the most common scripting mistakes?

In his excellent JavaScript Sourcebook, in a section that begins, "We're only human, after all, and making mistakes is part of our nature," Gordon McComb identifies eleven common JavaScript gaffs:

  • Omitting quotation marks in Strings
  • Mismatched quotation mark types (' and ")
  • Omitting quotation marks when comparing strings
  • Confusing '=' (assign) and '==' (compare)
  • Improperly nested blocks in IF-THEN-ELSE statements
  • Trying to write to the script document
  • Trying to access forms as a property of a window rather than a document
  • Using String methods with the wrong objects
  • Endless loops lock up the browser
  • Missing or mismatched '{' or '}' around blocks
  • Omitting the return() statement in a function

                                                                                                            BACK TO TOP

4. Why won't my script work ...

  1. ... inside a table?

There is a long-standing bug in JavaScript concerning tables. To be safe, Do not place <SCRIPT> tags inside <TD> tags. Instead, start the <SCRIPT> tag before the <TD> tag, and document.write() the <TD> tag through the </TD> tag. If you're a belt-and-suspenders kind of guy, you can go a step further by using document.write() to create the entire table , interlacing script statements where needed.

  1. ... under MS Internet Explorer 3 for the Mac?

JScript is available on the Macintosh starting with 3.0.1 (which is different from the Windows 3.01). I am still evaluating the Mac implementation, whose object model and other support for JavaScript does not necessarily jive with the Windows version (e.g., the Mac version supports the Image object for mouse rollovers). MSIE 3.0.1 runs on Mac 68K and PPC. Download it from: http://www.microsoft.com/msdownload/ieplatform/iemac.ht m

  1. ... under MSIE 3 for Windows 95?

Most language features and objects that are new in Navigator 3.0 are not supported in MSIE 3.0, although several Navigator 3.0 items have been added to JScript version 2 (see below).

  1. ... when I use document.cookie with MSIE?

It does work, but not when you access the HTML file from your local hard disk, as you are probably doing during testing. Be aware, however, that MSIE limits you to one cookie name=value pair per domain, whereas Netscape allows up to 20 pairs per domain.

                                                                                                            BACK TO TOP

5. Jscript Issues

What's new in Microsoft JScript version 2.x and 3.x?

More than can fit here. Some items are compatible with Navigator 3.0+ (such as the Array object). Others are unique to MSIE, such as the Dictionary and TextStream objects (accessible via ActiveX). Additions are to the core language, not the document object model.

New functions let you determine the JScript version installed in IE, but JScript version 2 must be installed to get this data. If you use version 2 or 3.x language features, see www.microsoft.com/JScript for info about including a link button on your page to encourage visitors to upgrade their IE 3.0x to JScript version 2.

How do I know if I have JScript version 2 installed?

Installation of MSIE 3.02 does not guarantee JScript version 2. Search your disk for 'jscript.dll'. Get the file's properties, and click on the Version tab. The File version should begin with '2'. If not, download the latest version from Microsoft (installer is 442KB).

What parts of the JavaScript object model are unsupported in MSIE?

UNSUPPORTED OBJECTS Image -- this means no onMouseOver swappable images in MSIE 3

Area -- no onMouseOvers

Applet

FileUpload

*Array -- hard-wired (JS1.0) arrays OK; implemented in JScript v.2.

MimeType

Plugin

What properties/methods/event handlers are unsupported in MSIE?

UNSUPPORTED PROPERTIES/METHODS/EVENT HANDLERS
OF SUPPORTED OBJECTS
 

Window

      onerror  closed  blur()  focus()  scroll()  onBlur=   onFocus=

Location

      reload()  replace()

Document

      applets[]  domain  embeds[]  images[]  URL

Link

      onMouseOut=

Form

      reset()  onReset=

All Form Elements

      type

Navigator

      mimeTypes[]  plugins[]  javaEnabled()

String

      prototype  split()

One more item: the <SCRIPT SRC="xxx.js"> facility for loading external JavaScript library files is available in MSIE 3.02 for Windows.

 

                                                                                                            BACK TO TOP

6. Portability

  1. Anyone have a comparison of MS JScript versus Netscape's JavaScript?

Mark Stone wrote the book on it:
http://www.kudonet.com/~markst/jscript/jsdiff.htm

  1. I thought JavaScript was turned over to the IETF for some sort of standardization. What's happening with this?

Actually it was "turned over" to ECMA, the European Computing Machine Association. They appear to be go-slow, secretive types. It remains to be seen whether this is a serious standardization effort, or a marketing ruse by Netscape to match Microsoft's dubious "turning over" of ActiveX to the X/Open Group.

                                                                                                            BACK TO TOP

Programming Tools

1. What is NetObjects ScriptBuilderTM?

A scripting development aid from NetObjects, Inc. In addition to JavaScript, ScriptBuilder facilitates code writing in VBScript, LotusScript and Microsoft ASP. Reviewed by IDM in June 1998.

                                                                                                            BACK TO TOP

2. What is Borland IntraBuilderTM?

IntraBuilder is a web application development tool from Inprise Corporation (formerly Borland International) that makes heavy use of JavaScript. Together with companion products C++Builder and JBuilder, IntraBuilder is part of the product line that implements Inprise's "Golden Gate" strategy for web-based client/server development.

Each product in this line targets three developer levels with Standard, Professional and Client/Server editions, corresponding respectively to low ($99), medium ($499) and high ($1999) price points. The increments buy enhanced database connectivity and features for managing team development.

IntraBuilder consists of two primary components:

IntraBuilder Designer, a visual RAD environment for JavaScript that creates Forms -- used for entering, displaying and manipulating data; and Reports -- used for displaying data in a list format that can include groupings and aggregate functions, such as totals or averages. Significantly for readers of this FAQ, IntraBuilder provides wizards that coach the developer through web page specification, then automatically generates standard JavaScript, including form elements and data validation routines.

IntraBuilder Server, which extends basic web server functionality to deliver data-driven pages. IntraBuilder Server uses three primary architectural components (diagrammed below): IntraBuilder Broker, IntraBuilder Agents, and the Borland Database Engine (BDE).

 

Larger version

The IntraBuilder Broker automatically provides the communications layer between the IntraBuilder Agents and the Web server, the first layer of state management, and intelligent routing.
IntraBuilder Agents automatically parse forms and reports, dynamically generate HTML, participate in state management, and manage data access and formatting.
The Borland Database Engine provides the database connectivity for IntraBuilder, connecting to a wide range of servers using native APIs and ODBC.

IntraBuilder belongs to a large, maturing class of web-to-database application development tools, several of which are listed in Intranet Journal's Gateways to Data section. IntraBuilder is specifically treated in this JavaScript FAQ because of the central role JavaScript plays in its design.

                                                                                                            BACK TO TOP

3. What is Netscape Visual JavaScript?

"A visual tool for rapid crossware development," according to its maker. Netscape defines crossware as "on-demand software that runs across networks, operating systems, and platforms and easily extends to partners and customers."

IDM has experimented with Preview Release 3 of Visual JavaScript 1.0. Functionally impressive, the product strikes us primarily as a weapon in Netscape's anti-Microsoft agenda, for three reasons:

  1.  
    • Visual JavaScript's emphasis on crossware and platform-independence directly oppose Microsoft's more vertical, Windows-based architecture
    • Visual JavaScript's GUI does not conform to Microsoft Windows style guidelines, despite being launched on Windows. Instead, the product appears to emulate the Unix/Motif look and feel of Sun Microsoystems' Java Workshop
    • multi-platform rhetoric notwithstanding, Visual JavaScript is tailored to interoperate primarily with services from Netscape’s SuiteSpot line of servers. Using a built-in component, for instance, you could call upon Netscape Messaging Server to send mail, or Netscape Directory Server to do an LDAP directory query. Microsoft's products in general -- and ActiveX components in particular -- are conspicuously absent from this message.

Lack of support for Microsoft technologies contrasts with Visual JavaScript's otherwise very impressive feature set, which lets developers:

  1.  
    • Author HTML with a built-in WYSIWYG Page Builder
    • Drag and drop components onto web pages from the extensible Component Palette, which includes CORBA/IIOP services
    • Customize components using Inspector to view and edit properties and events
    • Use visual, drag-and-drop programming to connect components
    • Debug applications using a built-in JavaScript debugger that lets you set breakpoints and step through code
    • Manage projects with multiple developers using Enterprise Server 3.0 content management system, which enables page check-in / check-out, version control, and shared component palettes
    • Tie into Oracle, Informix, Sybase, or ODBC databases using the included LiveWire JavaScript components, leveraging the built-in LiveWire Database Service in Enterprise Server 3.0.
    • Automatically invoke LiveWire compiler and Application Manager behind the scenes for web applications using server-side JavaScript.
    • The bundled Component Developer's Kit lets you write new components in JavaScript or Java (i.e., standard JavaBeans).

For more information, visit Netscape's web site, or better yet, download a trial release of Visual JavaScript and take its measure yourself.

                                                                                                            BACK TO TOP

4. Are there any JavaScript Debuggers?

Netscape bundles a debugger with Visual JavaScript.

The Microsoft Script Debugger is a debugging environment that extends any Microsoft ActiveX Scripting host application (for example, Internet Explorer or Internet Information Server).

                                                                                                            BACK TO TOP

Other Sources

  1. The latest version of the semi-official JavaScript mini-FAQ is always available in the language's newsgroup, comp.lang.javascript. It's principal author, Danny Goodman, has written many classic computer books, including JavaScript Bible, 3rd Ed. (IDG Books, March 1998). His site is a well-organized clearinghouse for JavaScript routines.
  2. A "webmaster's learning center," George Chiang's Website Abstraction, at www.wsabstract.com is a well organized site featuring JavaScript tutorials and free code samples.
  3. A more basic tutorial, JavaScript for the Total Non-Programmer, is hosted by itinerant webteacher Rob Young at:
    www.webteacher.com/javatour.htm.
  4. The JavaScript Source is an ever-growing collection of hundreds of free JavaScripts that are available for unrestricted use on your web pages.
  5. Martin Webb's irt.org site is "a non-profit making online developer site that covers Internet Related Technologies that are cross-browser as well as operating system and platform independent." Copious, up-to-date information on JavaScript, ECMAScript and VBScript.
  6. Dynamic Drive is a quality source of free, original DHTML scripts and components. There are some copyright restrictions, so read the Terms of Use carefully before indulging.
  7. For a solid library of sample JavaScript apps check out HotSyte - The JavaScript Resource. Important subsections include The HotSyte Reserve and Tim Wildman's Script Archive.
  8. Following is a list of several more of our favorite online scripting resources. If you think we missed an important one, tell the editor.
  9. Netscape's Frames Tutorial - An Introduction
  10. Netscape tutorial on Client Side State - HTTP Cookies
  11. HTTP, CGI reference sites
    The NCSA HTTPd Home Page
    Apache HTTP Server Project

 

 

For more details visit Intranet Journal at

http://www.intranetjournal.com/faq/js-faq.shtml

http://idm.internet.com/index.html

COBOL FAQ

Wednesday, March 25th, 2009

1. What is a reentrant program? How will you make a program Reentrant?

A. A reentrant program, while being executed resides in the common virtual area so that one copy of it may be shared among all callers. Use RENT compiler option.

2. What is the difference between a 01 level and 77 level?

A. 01 level can have sublevels from 02 to 49. 77 cannot have sublevel.

3. What are the few advantages of VS COBOL II over OS/VS COBOL?

A. The working storage and linkage section limit has been increased. They are 128 megabytes as supposed to 1 megabytes in OS/VS COBOL. Introduction of ADDRESS special register.

31-bit addressing. In using COBOL on PC we have only flat files and the programs can access only limited storage, whereas in VS COBOL II on M/F the programs can access up to 16MB or 2GB depending on the addressing and can use VSAM files to make I/O operations faster.

4. What are the steps you go through while creating a COBOL program executable?

A. DB2 pre-compiler (if embedded SQL is used), CICS translator (if CICS program), Cobol compiler, Link editor. If DB2 program, create plan by binding the DBRMs.

5. What are the minimum requirements to compile a program without errors?

A. Identification Division.

Program-ID. Program-name.

A) Is compute w=u a valid statement?

Yes, it is. It is equivalent to move u to w.

B) In the above example, when will you prefer compute statement over the move statement?

When significant left-order digits would be lost in execution, the COMPUTE statement can detect the condition and allow you to handle it. The MOVE statement carries out the assignment with destructive truncation. Therefore, if the size error is needs to be detected, COMPUTE will be preferred over MOVE. The ON SIZE ERROR phrase of COMPUTE statement, compiler generates code to detect size-overflow.

6. What happens when the ON SIZE ERROR phrase is specified on a COMPUTE statement?

A. If the condition occurs, the code in the ON SIZE ERROR phrase is performed, and the content of the destination field remains unchanged. If the ON SIZE ERROR phrase is not specified, the assignment is carried out with truncation. There is no ON SIZE ERROR support for the MOVE statement.

7. How will you associate your files with external data sets where they physically reside?

A. Using SELECT clause, the files can be associated with external data sets. The SELECT clause is defined in the FILE-CONTROL paragraph of Input-Output Section that is coded Environment Division. The File structure is defined by FD entry under File-Section of Data Division for the OS.

8. How will you define your file to the operating system?

A. Associate the file with the external data set using SELECT clause of INPUT-OUTPUT SECTION. INPUT-OUTPUT SECTION appears inside the ENVIRONMENT DIVISION.

Define your file structure in the FILE SECTION of DATA DIVISION.

9. Explain the use of Declaratives in COBOL?

  1. Declaratives provide special section that are executed when an exceptional condition occurs. They must be grouped together and coded at the beginning of procedure division and the entire procedure division must be divided into sections. The Declaratives start with a USE statement. The entire group of declaratives is preceded by DECLARIVES and followed by END DECLARITIVES in area A. The three types of declaratives are Exception (when error occurs during file handling), Debugging (to debug lines with ‘D’ coded in w-s section) and Label (for EOF or beginning…) declaratives.

10. A statically bound subprogram is called twice. What happens to working-storage variables?

A. The working-storage section is allocated at the start of the run-unit and any data items with VALUE clauses are initialized to the appropriate value at the time. When the subprogram is called the second time, a working-storage items persist in their last used state. However, if the program is specified with INITIAL on the PROGRAM-ID, working-storage section is reinitialized each time the program is entered.

PROGRAM-ID. <Pgmname> is INITIAL PROGRAM. Other verbs used with PROGRAM-ID are RECURSIVE and COMMON.

11. When is COMMON attribute used?

A. COMMON attribute is used with nested COBOL programs. If it is not specified, other nested programs will not be able to access the program. PROGRAM-ID. Pgmname is COMMON PROGRAM.

12. In which division and section, the Special-names paragraph appears?

A. Environment division and Configuration Section.

13. What is the LOCAL-STORAGE SECTION?

A. Local-Storage is allocated each time the program is called and is de-allocated when the program returns via an EXIT PROGRAM, GOBACK, or STOP RUN. Any data items with a VALUE clauses are initialized to the appropriate value each time the program is called. The value in the data items is lost when the program returns. It is defined in the DATA DIVISION after WORKING-STORAGE SECTION

14. What does passing BY REFERENCE mean?

A. When the data is passed between programs, the subprogram refers to and processes the data items in the calling program’s storage, rather than working on a copy of the data. When

CALL . . . BY REFERENCE identifier. In this case, the caller and the called share the same memory.

15. What does passing BY CONTENT mean?

A. The calling program passes only the contents of the literal, or identifier. With a CALL . . . BY CONTENT, the called program cannot change the value of the literal or identifier in the calling program, even if it modifies the variable in which it received the literal or identifier.

16. What does passing BY VALUE mean?

A. The calling program or method is passing the value of the literal, or identifier, not a reference to the sending data item. The called program or invoked method can change the parameter in the called program or invoked method. However, because the subprogram or method has access only to a temporary copy of the sending data item, those changes do not affect the argument in the calling program. Use By value, If you want to pass data to C program. Parameters must be of certain data type.

17. What is the default, passing BY REFERENCE or passing BY CONTENT or passing BY VALUE?

A. Passing by reference (the caller and the called share the same memory).

18. Where do you define your data in a program if the data is passed to the program from a Caller program?

A. Linkage Section

19. Define the structure of a COBOL subroutine.

A. The PROCEDURE DIVISION header must have a using a phrase, if the data needs to be passed to the program. The operands of the USING phrase must be defined in the LINKAGE SECTION as 01-level or 77-level entries. No VALUE clause is allowed unless the data defined is a condition name.

If the program needs to be returned to the CALLER, use EXIT PROGRAM statement at the end of the program. GOBACK is an alternative, but is nonstandard.

20. What is difference between next sentence and continue

A. NEXT SENTENCE gives control to the verb following the next period. CONTINUE gives control to the next verb after the explicit scope terminator. (This is not one of COBOL II’s finer implementations). It’s safest to use CONTINUE rather than NEXT SENTENCE in COBOL II. CONTINUE is like a null statement (do nothing) , while NEXT SENTENCE transfers control to the next sentence (!!) (A sentence is terminated by a period). Check out by writing the following code example, one if sentence followed by 3 display statements: If 1 > 0 then next sentence end if display ‘line 1′ display ‘line 2′. display ‘line 3′. *** Note- there is a dot (.) only at the end of the last 2 statements, see the effect by replacing Next Sentence with Continue ***

21. What is the difference between Structured Cobol Programming and Object Oriented COBOL programming?

A. Structured programming is a Logical way of programming using which you divide the functionality’s into modules and code logically. OOP is a Natural way of programming in which you identify the objects, first then write functions and procedures around the objects. Sorry, this may not be an adequate answer, but they are two different programming paradigms, which is difficult to put in a sentence or two.

22. PIC S9(4)COMP IS USED INPSPITE OF COMP-3 WHICH OCCUPIES LESS SPACE.WHY?

A. S9(4) COMP uses only 2 bytes. 9(4) COMP-3 uses 3 bytes. 3 bytes are more than 2 bytes. Hence COMP is preferred over COMP-3 in this case.

23. How many number of bytes and digits are involved in S9(10) COMP?

  1. 8 bytes (double word) and 10 digits. Up to 9(9) comp use full word, up to 9(18) comp needs double word.

24. Which picture clause will you use to define a hexadecimal item in a VALUE clause?

A. 01 ws-hexitem PIC X(2) value X’020C’.

01 ws-hex redefines PIC S9(3) comp-3.

25. How many numbers of decimal digits are possible, when the amount of storage allocated for a USAGE COMP item is a) half word b) full word c) double word?

A. 2 bytes (halfword) for 1-4 Digits 4 bytes (fullword) for 5-9

8 bytes (doubleword) for 10-18

26. What is a scope terminator? Give examples.

  1. Scope terminator is used to mark the end of a verb e.g. EVALUATE, END-EVALUATE; IF, END-IF.

27. How many dimensions are allowed for a table?

A. 7

28. How many subscripts or indexes are allowed for an OCCURS clause?

A. 7

29. Why cannot Occurs be used in 01 level?

A. Because, Occurs clause is there to repeat fields with the same format, but not the records.

30. Can a REDEFINES clause be used along with an OCCURS clause?

A. Yes, if the REDEFINES clause is subordinate to OCCURS clause.

31. Can you specify PIC clause and a VALUE with an OCCURS clause? Will the following code compile without errors?

01 WS-TABLE.

03 WS-TABLE-EL OCCURS 5 TIMES PIC X(1) VALUE SPACES.

A. Yes, the code will compile without any errors.

32. What would be the output, when the following code is executed?

01 WS-TABLE.

03 WS-TABLE-EL OCCURS 5 TIMES PIC X(1) VALUE ‘AAAAA’.

A. It cannot be executed because the code will compile with error ‘ “VALUE” literal “‘AAAA’” exceeded the length specified in the “PICTURE” definition’.

33. 01 WS-TABLE.

03 WS-TABLE-EL OCCURS 5 TIMES PIC X(1) VALUE ‘A’.

03 WS-EX REDEFINES WS-TABLE-EL PIC X(5). What can you expect?

A. Compile error. Direct Redefinition of OCCURS clause is not allowed.

34. 01 WS-TABLE.

03 WS-TABLE-EL OCCURS 5 TIMES.

04 FILLER-X PIC X(1) VALUE ‘A’. 04 WS-EX REDEFINES FILLER-X PIC X(1).

What would be the output of DISPLAY WS-TABLE?

A. ‘AAAAA’. The code will compile and execute as Redefinition of an item subordinate to OCCURS clause.

35. Is this allowed?

01 WS-TABLE.

03 FILLER-X PIC X(5) VALUE ‘AAAAA’.

03 WS-EX REDEFINES FILLER-X.

04 WS-TABLE-EL OCCURS 5 TIMES PIC X(1).

A. Yes

35. Is this allowed?

01 WS-TABLE.

03 FILLER-X PIC X(5) VALUE ‘AAAAA’.

03 WS-EX REDEFINES FILLER-X OCCURS 5 TIMES PIC X(1).

A. Yes

36. Which SEARCH verb is equivalent to PERFORM…VARYING?

  1. The serial SEARCH verb (SEARCH without ALL)

37. What would be the output, when the following code is executed?

01 WS-TABLE.

03 WS-TABLE-EL OCCURS 5 TIMES PIC X(1) VALUE ‘A’.

:::

DISPLAY WS-TABLE.

A. The output will display ‘AAAAA’

38. Can a SEARCH be applied to a table which does not have an INDEX defined?

A. No, the table must be indexed.

39. What are the different rules applicable to perform a serial SEARCH?

A. The SEARCH can be applied to only a table which has the OCCURS clause and INDEXED BY phrase,

Before the use of the SEARCH the index must have some initial value. To search from beginning, set the index value to 1. Use the SEARCH verb without ALL phrase

40. A table has two indexes defined. Which one will be used by the SEARCH verb?

A. The index named first will be used, by Search.

41. What are the different rules applicable to perform a binary SEARCH?

A. The table must be sorted in ascending or descending order before the beginning of the SEARCH. Use OCCURS clause with ASC/DESC KEY IS dataname1 option

The table must be indexed. There is no need to set the index value. Use SEARCH ALL verb

42. How does the binary search work?

A. First the table is split into two halves and in which half, the item need to be searched is determined. The half to which the desired item may belong is again divided into two halves and the previous procedure is followed. This continues until the item is found. SEARCH ALL is efficient for tables larger than 70 items.

43. What is the difference between a binary search and a sequential search? What are the pertinent COBOL commands?

A. In a binary search the table element key values must be in ascending or descending sequence. The table is ‘halved’ to search for equal to, greater than or less than conditions until the element is found. In a sequential search the table is searched from top to bottom, so (ironically) the elements do not have to be in a specific sequence. The binary search is much faster for larger tables, While sequential Search works well with smaller ones. SEARCH ALL is used for binary searches; SEARCH for sequential.

44. Explain the difference between an internal and an external sort. The pros & cons & internal sort syntax …

A. An external sort is not coded as a COBOL program; it is performed through JCL and PGM=SORT. One can use IBM utility SYNCSORT for external sort process. It is understandable without any code reference. An internal sort can use two different syntaxes: 1.) USING, GIVING sorts are comparable to external sorts with no extra file processing; 2) INPUT PROCEDURE, OUTPUT PROCEDURE sorts allow for data manipulation before and/or after the sort. Syntax:

  • SORT file-1 ON ASCENDING/DESCENDING KEY key…USING file-2 GIVING file-3.
  • USING can be substituted by INPUT PROCEDURE IS para-1 THRU para-2
  • GIVING can be substituted by OUTPUT PROCEDURE IS para-1 THRU para-2.
  • file-1 is the sort workfile and must be described using SD entry in FILE SECTION.
  • file-2 is the input file for the SORT and must be described using an FD entry in FILE SECTION and SELECT clause in FILE CONTROL.
  • file-3 is the outfile from the SORT and must be described using an FD entry in FILE SECTION and SELECT clause in FILE CONTROL.
  • file-1, file-2 & file-3 should not be opened explicitly.
  • INPUT PROCEDURE is executed before the sort and records must be RELEASEd to the sort work file from the input procedure.
  • OUTPUT PROCEDURE is executed after all records have been sorted. Records from the sort work file must be RETURNed one at a time to the output procedure.
  • .How do you define a sort file in JCL that runs the COBOL program?
  • Use the SORTWK01, SORTWK02,….. dd names in the step. Number of sort datasets depends on the volume of data being sorted, but a minimum of 3 is required.

45. Which is the default, TEST BEFORE or TEST AFTER for a PERFORM statement?

  1. TEST BEFORE. By default the condition is checked before executing the instructions under Perform.

46. What is the difference between PERFORM … WITH TEST AFTER and PERFORM … WITH TEST BEFORE?

A. If TEST BEFORE is specified, the condition is tested at the beginning of each repeated execution of the specified PERFORM range. If TEST AFTER is specified, the condition is tested at the end of the each repeated execution of the PERFORM range. With TEST AFTER, the range is executed at least once.

47. How do you code an in-line PERFORM?

A. PERFORM … <UNTIL> … <statements> END-PERFORM.

48. In an EVALUTE statement is the order of the WHEN clauses significant?

  1. Yes. Evaluation of the WHEN clauses proceeds from top to bottom and their sequence can determine results.

49. What is the default value(s) for an INITIALIZE and what keyword allows for an override of the default.

A. INITIALIZE sets spaces to alphabetic and alphanumeric fields. Initialize sets Zeroes to numeric fields. FILLER, OCCURS DEPENDING ON items are left untouched. The REPLACING option can be used to override these defaults.

50. What is SET <condition-name> TO TRUE all about, anyway?

A. In COBOL II the 88 levels can be set rather than moving their associated values to the related data item. (Web note: This change is not one of COBOL II’s better specifications.)

51. What is LENGTH in COBOL II?

A. LENGTH acts like a special register to tell the length of a group or an elementary item.

52. What is the function of a delimiter in STRING?

A. A delimiter in STRING causes a sending field to be ended and another to be started.

53. What is the function of a delimiter in UNSTRING?

A. A delimiter when encountered in the sending field causes the current receiving field to be switched to the next one indicated.

54. How will you count the number of characters in a null-terminated string?

A. MOVE 0 TO char-count

INSPECT null-terminated-string TALLYING char-count FOR CHARACTERS BEFORE X”00″

55. Which statement will you use to move non-null characters from a null-terminated String?

A. UNSTRING null-terminated-string DELIMITED BY X”00″ INTO target-area

COUNT IN char-count. (There are other methods, such as 1) using PERFORM 2) using SEARCH 3) using INSPECT and MOVE etc…)

56. 77 COUNTR PIC 9 VALUE ZERO.

01 DATA-2 PIC X(11). . .

INSPECT DATA-2

TALLYING COUNTR FOR LEADING “0″

REPLACING FIRST “A” BY “2″ AFTER INITIAL “C”

If DATA-2 is 0000ALABAMA, what will DATA-2 and COUNTER be after the execution of INSPECT verb?

A.       Counter=4.             Data-2 will not change as the Initial 'C' is not found.

57. 01 DATA-4 PIC X(11).

:::

INSPECT DATA-4 CONVERTING

“abcdefghijklmnopqrstuvwxyz” TO “ABCDEFGHIJKLMNOPQRSTUVWXYZ”

AFTER INITIAL “/” BEFORE INITIAL”?”

What will the contents of DATA-4 be after the conversion statement is performed, if before conversion

a) DATA-4 = a/five/?six b) DATA-4 = r/Rexx/RRRr c) DATA-4 = zfour?inspe

A. a) a/FIVE/?six b) r/REXX/RRRR c) zfour?inspe (no change at all)

58. What kind of error is trapped by ON SIZE ERROR option?

A. Fixed-point overflow. Zero raised to the zero power.

Division by 0. Zero raised to a negative number.

A negative number raised to a fractional power.

 59. What is the point of the REPLACING option of a copy statement?

A. REPLACING allows for the same copy to be used more than once in the same code by changing the replace value. COPY xxx REPLACING <psuedotext1> BY <psuedotext2>.

60. When is a scope terminator mandatory?

A. Scope terminators are mandatory for in-line PERFORMS and EVALUATE statements. For readability, it’s recommended coding practice to always make scope terminators explicit.

61. Can you use REDEFINES clause in the FILE SECTION?

A. No

62. How will you define your record descriptions in the FILE SECTION if you want to use three different record descriptions for the same file?

A. FD filename

DATA RECORDS ARE rd01, rd02, rd03.

01 rd01 PIC X(n).

01 rd02 PIC X(n).

01 rd03 PIC X(n).

63. When will you open a file in the EXTEND mode?

A. When an existing file should be appended by adding new records at its end. EXTEND mode opens the file for output, but the file is positioned following the last record on the existing file.

64. What does a CLOSE WITH LOCK statement do?

A. The statement closes an opened file and it prevents the file from further being opened by the same program.

65. Which mode of opening is required when REWRITE is used?

A. I-O mode

66. Why is it necessary that the file be opened in I-O mode for REWRITE?

A. Before the REWRITE is performed, the record must be read from the file. Hence REWRITE includes an input operation and an output operation. Therefore, the file must be opened in I-O mode.

67. Which clause can be used instead of checking for FILE STATUS = 10?

A. FILE STATUS 10 is the end of file condition. Hence AT END clause can be used.

68. What is the format of a simple SORT verb? What kinds of files can be sorted using SORT?

A. SORT workfile ON ASC/DESC KEY key1, ASC/DESC KEY key2 …

USING inputfile GIVING outputfile

Only sequential files can be sorted in this way.

69. What are the different rules of SORT that needs to be considered?

  1. The input and output files must remain closed because SORT opens them and closes during the operation, The work file must have a SELECT clause. The work file must have sort description SD entry in the FILE SECTION. Input and Output files must have FD entries

70. What are INPUT PROCEDURE and OUTPUT PROCEDURE?

A. Sometimes, it is necessary that the records must be edited before or after the sorting. In such cases,

SORT workfile ASC/DESC KEY key1, …

INPUT PROCEDURE IS ipproc

OUTPUT PROCEDURE is outproc

Is used. In the INPUT PROCEDURE the input file is opened, records are read and edited and then are released to the sorting operation. Finally the file is closed. RELEASE sortrecname FROM inp-rec.

In the OUTPUT PROCEDURE, output file is opened, the sorted record is returned to the Output record area and then the record is written. Finally the file is closed. RETURN workfile RECORD into out-rec.

71. What is the format of a simple MERGE verb? Can INPUT PROCEDURE and OUTPUT PROCEDURE can be specified for MERGE verb?

A. MERGE work file ON ASC/DESC KEY key1…

USING inputfile1, inputfile2…

GIVING outputfile

INPUT PROCEDURE cannot be specified. Only OUTPUT PROCEDURE can be specified

72. How will you position an indexed file at a specific point so that the subsequent sequential operations on the file can start from this point?

A. Use START

START filename KEY IS EQ/GT/LT.. dataname

INVALID KEY …

73. What are the access mode requirements of START statement?

A. Access mode must be SEQUENTIAL or DYNAMIC

74. What are the opening mode requirements of START statement?

  1. Files must be opened in the INPUT or I-O mode.

75.What is the LINKAGE SECTION used for?

A. The linkage section is used to pass data from one program to another program or to pass data from a PROC to a program. It is part of a called program that ‘links’ or maps to data items in the calling program’s working storage. It is the part of the called program where these share items are defined.

76. If you were passing a table via linkage, which is preferable – a subscript or an index?

A. Wake up – you haven’t been paying attention! It’s not possible to pass an index via linkage. The index is not part of the calling programs working storage. Indexing uses binary displacement. Subscripts use the value of the occurrence.

77. What is the difference between a subscript and an index in a table definition?

  1. A subscript is a working storage data definition item, typically a PIC (999) where a value must be moved to the subscript and then increment or decrement it by ADD TO and SUBTRACT FROM statements. An index is a register item that exists outside the program’s working storage. You SET an index to a value and SET it UP BY value and DOWN BY value.

Subscript refers to the array occurrence while index is the displacement (in no of bytes) from the beginning of the array. An index can only be modified using PERFORM, SEARCH & SET. Need to have index for a table in order to use SEARCH, SEARCH ALL Cobol statements.

78. What is an in line PERFORM? When would you use it? Anything else to say about it?

  1. The PERFORM and END-PERFORM statements bracket all COBOL II statements between them. The COBOL equivalent is to PERFORM or PERFORM THRU a paragraph. In line PERFORMs work as long as there are no internal GO TOs, not even to an exit. The in line PERFORM for readability should not exceed a page length – often it will reference other PERFORM paragraphs.

When the body of the Perform will not be used in other paragraphs. If the body of the Perform is a generic type of code (used from various other places in the program), it would be better to put the code in a separate para and use PERFORM paraname rather than in-line perform.

79. What is the use of EVALUATE statement? How do you come out of an EVALUATE statement?

A. Evaluate is like a case statement and can be used to replace nested Ifs. The difference between EVALUATE and case is that no ‘break’ is required for EVALUATE i.e. control comes out of the EVALUATE as soon as one match is made, There is no need of any extra code. EVALUATE can be used in place of the nested IF THEN ELSE statements.

80. What are the different forms of EVALUATE statement?

A. EVALUATE EVALUATE SQLCODE ALSO FILE-STATUS

WHEN A=B AND C=D WHEN 100 ALSO ‘00′

Imperative stmt imperative stmt

WHEN (D+X)/Y = 4 WHEN -305 ALSO ‘32′

imperative stmt imperative stmt

WHEN OTHER WHEN OTHER

imperative stmt imperative stmt

END-EVALUATE END-EVALUATE

 

EVALUATE SQLCODE ALSO A=B EVALUATE SQLCODE ALSO TRUE

WHEN 100 ALSO TRUE WHEN 100 ALSO A=B

imperative stmt imperative stmt

WHEN -305 ALSO FALSE WHEN -305 ALSO (A/C=4)

imperative stmt imperative stmt

END-EVALUATE END-EVALUATE

81. Can you use the INSPECT (with TALLYING option) Cobol verb in a CICS COBOL program?

A. Yes, under COBOL II environment, but not OS/VS COBOL.

82. What is an explicit scope terminator?

  1. A scope terminator brackets its preceding verb, eg. IF .. END-IF, so that all statements between the verb and its scope terminator are grouped together. Other common COBOL II verbs are READ, PERFORM, EVALUATE, SEARCH and STRING.

83. What is the significance of ‘above the line’ and ‘below the line’?

A. Before IBM introduced MVS/XA architecture in the 1980’s a program’s virtual storage was limited to 16 megs. Programs compiled with a 24-bit mode can only address 16 MB of space, as though they were kept under an imaginary storage line. With COBOL II a program compiled with a 31 bit mode can be ‘above the 16 Mb line. (This ‘below the line’, ‘above the line’ imagery confuses most mainframe programmers, who tend to be a literal minded group.)

84. What was removed from COBOL in the COBOL II implementation?

A. Partial list: REMARKS, NOMINAL KEY, PAGE-COUNTER, CURRENT-DAY, TIME-OF-DAY, STATE, FLOW, COUNT, EXAMINE, EXHIBIT, READY TRACE and RESET TRACE.

85. Explain call by context by comparing it to other calls.

A. The parameters passed in a call by context are protected from modification by the called program. In a normal call they are able to be modified.

86. What is the difference between comp and comp-3 usage? Explain other COBOL usages.

  1. Comp is a binary usage, while comp-3 indicates packed decimal. The other common usages are binary and display. Display is the default. Comp is defined as the fastest/preferred numeric data type for the machine it runs on. IBM Mainframes are typically binary and AS400’s are packed.’

87. I understand the possible causes for S0C1 & S0C4 abends, but what are they really?

A. A S0C1 occurs if the CPU attempts to execute binary code that isn’t a valid machine instruction; e.g. if you attempt to execute data. A S0C4 is a memory protection violation. This occurs if a program attempts to access storage beyond the areas assigned to it.

88. What happens when we move a comp-3 field to an edited ( say z(9).zz-)

A. The editing characters are to be used with data items with usage clause as display, which is the default. When you try displaying a data item with usage as computational it does not give the desired display format because the data item is stored as packed decimal. So if u want this particular data item to be edited u have to move it into a data item whose usage is display and then have that particular data item edited in the format desired.

89. What are the causes for S0C1, S0C4, S0C5, S0C7, S0CB abends

  1. S0C1 – May be due to 1.Missing or misspelled DD name 2.Read/Write to unopened dataset 3.Read to dataset opened output 4.Write to dataset opened input 5.Called subprogram not found.

S0C4 may be due to 1.Missing Select statement(during compile) 2.Bad Subscript/index 3.Protection Exception 4.Missing parameters on called subprogram 5.Read/Write to unopened file 6.Move data from/to unopened file.

S0C5 May be due to 1.Bad Subscript/index 2.Close an unopen dataset 3.Bad exit from a perform 4.Access to I/O area(FD) before read.

S0C7 may be due to 1.Numeric operation on non-numeric data 2.Un-initialize working-storage 3.Coding past the maximum allowed sub script. S0CB may be due to 1.Division by Zero

90. What will happen if you code GO BACK instead of STOP RUN in a stand-alone COBOL program i.e. a program which is not calling any other program.

  1. Both give the same results when a program is not calling any other program.

91. What is the difference between an External and a Global Variable ’s?

A. Global variables are accessible only to the batch program whereas external variables can be referenced from any batch program residing in the same system library.

92. WHAT IS REPORT-ITEM?

A. A REPORT-item is a field to be printed that contains EDIT SYMBOLS

93. You are writing report program with 4 levels of totals:city,state,region and country. The codes being used can be the same over the different levels, meaning a city code of 01 can be in any number of states, and the same applies to state and region code show. Do you do your checking for breaks and how do you do add to each level?

  1. Always compare on the highest-level first, because if you have a break at a highest level, each level beneath it must also break. Add to the lowest level for each rec but add to the higher level only on break.

94. What is PSB & ACB?

A. PSB : Program specification block. Inform about how a specific program is to be access one or more IMS DB. It consists of PCB(Prg Communication Block). Information to which segment in DB can be accessed, what the program is allowed to do with those segment and how the DB is to be accessed. ACB : Access Control Blocks are generated by IMS as an expansion of information contained in the PSB in order to speed up the access to the applicable DBD’s.

95. What’s a LDS(Linear Data Set) and what’s it used for ?

A. LDS is a VSAM dataset in name only. It has unstructured 4k (4096 bytes) fixed size CIs which do not contain control fields and therefore from VSAM’s standpoint they do not contain any logical records. There is no freespace, and no access from Cobol. Can be accessed by DB2 and IMS fast path datasets. LDS is essentially a table of data maintained on disk. The ‘table entries’ must be created via a user program and can only be logically accessed via a user program. When passed, the entire LDS must be mapped into storage, then data is accessed via base and displacement type processing.

96. What is the Importance of GLOBAL clause According to new standards of COBOL

A. When any data name, file-name , Record-name, condition name or Index defined in an Including Program can be referenced by a directly or indirectly in an included program, Provided the said name has been declared to be a global name by GLOBAL Format of Global Clause is01 data-1 PIC 9(5) IS GLOBAL.

97. What is the Purpose of POINTER Phrase in STRING command

A. The Purpose of POINTER phrase is to specify the leftmost position within receiving field where the first transferred character will be stored

98.How do we get currentdate from system with century?

A. By using Intrinsic function, FUNCTION CURRENT-DATE

 

99.what is the difference between search and search all in the table handling?

A. Search is a linear search and search all is a binary search.

100.What is the maximum length of a field you can define using COMP-3?

A. 10 Bytes (S9(18) COMP-3).

101.How many Sections are there in Data Division?.

A. SIX SECTIONS 1.’FILE SECTION’ 2.’WORKING-STORAGE SECTION’ 3.’LOCAL-STORAGE SECTION’ 4.’SCREEN SECTION’ 5.’REPORT SECTION’ 6.’LINKAGE SECTION’

In COBOL II, there are only 4 sections. 1.’FILE SECTION’ 2.’WORKING-STORAGE SECTION’ 3.’LOCAL-STORAGE SECTION’ 4.’LINKAGE SECTION’.

102.How can I tell if a module is being called DYNAMICALLY or STATICALLY?

A. The ONLY way is to look at the output of the linkage editor (IEWL)or the load module itself. If the module is being called DYNAMICALLY then it will not exist in the main module, if it is being called STATICALLY then it will be seen in the load module. Calling a working storage variable, containing a program name, does not make a DYNAMIC call. This type of calling is known as IMPLICITE calling as the name of the module is implied by the contents of the working storage variable. Calling a program name literal (CALL).

103.What is the difference between a DYNAMIC and STATIC call in COBOL.

A. To correct an earlier answer:All called modules cannot run standalone if they require program variables passed to them via the LINKAGE section. DYNAMICally called modules are those that are not bound with the calling program at link edit time (IEWL for IBM) and so are loaded from the program library (joblib or steplib) associated with the job. For DYNAMIC calling of a module the DYNAM compiler option must be chosen, else the linkage editor will not generate an executable as it will expect null address resolution of all called modules. A STATICally called module is one that is bound with the calling module at link edit, and therefore becomes part of the executable load module.

104.What is the difference between PIC 9.99 and 9v99?

A. PIC 9.99 is a FOUR-POSITION field that actually contains a decimal point where as PIC 9v99 is THREE-POSITION numeric field with implied or assumed decimal position.

105.How is PIC 9.99 is different from PIC 9v99?

A. PIC 9.99 is a four position field that actually contains a decimal point where as 9v99 is a three position numeric field with an implied or assumed decimal point.

106.what is Pic 9v99 Indicates?

A. PICTURE 9v99 is a three position Numeric field with an implied or assumed decimal point after the first position; the v means an implied decimal point.

107.what guidelines should be followed to write a structured COBOL program?

  1. 1) Use ‘EVALUATE’ stmt for constructing cases. 2) Use scope terminators for nesting. 3)Use in-line Perform stmt for writing ‘do ‘ constructions. 4) Use Test Before and test after in the Perform stmt for writing Do-While constructions.

108.Read the following code.

01 ws-n PIC 9(2) value zero.

a-para.

move 5 to ws-n.

perform b-para ws-n times.

b-para.

move 10 to ws-n.

How many times will b-para be executed ?

A. 5 Times only. it will not take the value 10 that is initialized in the loop.

109.What are some examples of command terminators?

A. END-IF, END-EVALUATE

 

110.What care has to be taken to force program to execute above 16 Meg line?

A. Make sure that link option is AMODE=31 and RMODE=ANY. Compile option should never have SIZE(MAX).BUFSIZE can be 2K, efficient enough.

111.Give some advantages of REDEFINES clause.

A. You can REDEFINE a Variable from one PICTURE class to another PICTURE class by using the same memory location. By REDEFINES we can INITIALISE the variable in WORKING-STORAGE Section itself.3. We can REDEFINE a Single Variable into so many sub-variables.(This facility is very useful in solving Y2000 Problem.)

 

112.Why do we code s9(4)comp. Inspite of knowing comp-3 will occupy less space.

A. Here s9(4)comp is small integer ,so two words equal to 8 bytes. Totally it will occupy 2 bytes(4 words).here in s9(4) comp-3 as one word is equal to 1/2 byte.4 words equal to 2 bytes and sign will occupy 1/2 bytes totally it will occupy 3 bytes.

 

113.The maximum number of dimensions that an array can have in COBOL-85 is ________.

Answer: SEVEN in COBOL – 85 and THREE in COBOL – 84

114.Name the divisions in a COBOL program.

A. IDENTIFICATION DIVISION, ENVIRONMENT DIVISION, DATA DIVISION, PROCEDURE DIVISION.

115.What are the different data types available in COBOL?

A. Alpha-numeric (X), alphabetic (A) and numeric (9).

116.What is 77 level used for ?

A. Elementary level item. Cannot be subdivisions of other items (cannot be qualified), nor can they be subdivided themselves.

117.What is 88 level used for ?

A. For defining condition names.

118.What is level 66 used for ?

A. For RENAMES clause.

119.What does the IS NUMERIC clause establish?

A. IS NUMERIC can be used on alphanumeric items, signed numeric & packed decimal items and unsigned numeric & packed decimal items. IS NUMERIC returns TRUE if the item only consists of 0-9. However, if the item being tested is a signed item, then it may contain 0-9, + and – .

120.My program has an array defined to have 10 items. Due to a bug, I find that even if the program access the 11th item in this array, the program does not abend. What is wrong with it?

A. Must use compiler option SSRANGE if you want array bounds checking. Default is NOSSRANGE.

121. What is the difference between performing a SECTION and a PARAGRAPH?

A. Performing a SECTION will cause all the paragraphs that are part of the section, to be performed.

Performing a PARAGRAPH will cause only that paragraph to be performed.

122.Can I redefine an X(200) field with a field of X(100) ?

  1. Yes.

123.What does EXIT do?

A. Does nothing ! If used, must be the only sentence within a paragraph.

124.Can I redefine an X(100) field with a field of X(200)?

A. Yes. Redefines just causes both fields to start at the same location. For example:

01 WS-TOP PIC X(1)

01 WS-TOP-RED REDEFINES WS-TOP PIC X(2).

If you MOVE ‘12′ to WS-TOP-RED,

DISPLAY WS-TOP will show 1 while

DISPLAY WS-TOP-RED will show 12.

125.Can I redefine an X(200) field with a field of X(100) ?

A. Yes.

126.What do you do to resolve SOC-7 error?

A. Basically you need to correcting the offending data. Many times the reason for SOC7 is an un-initialized numeric item. Examine that possibility first. Many installations provide you a dump for run time abends ( it can be generated also by calling some subroutines or OS services thru assembly language). These dumps provide the offset of the last instruction at which the abend occurred. Examine the compilation output XREF listing to get the verb and the line number of the source code at this offset. Then you can look at the source code to find the bug. To get capture the runtime dumps, you will have to define some datasets (SYSABOUT etc ) in the JCL. If none of these are helpful, use judgement and DISPLAY to localize the source of error. You may even use batch program debugging tools.

127.How is sign stored in Packed Decimal fields and Zoned Decimal fields?

A. Packed Decimal fields: Sign is stored as a hex value in the last nibble (4 bits ) of the storage. Zoned Decimal fields: As a default, sign is over punched with the numeric value stored in the last bite.

128.How is sign stored in a comp-3 field?

A. It is stored in the last nibble. For example if your number is +100, it stores hex 0C in the last byte, hex 1C if your number is 101, hex 1D if the number is -101, hex 2D if the number is -102 etc…

129.How is sign stored in a COMP field ?

A. In the most significant bit. Bit is on if -ve, off if +ve.

130.What is the difference between COMP & COMP-3 ?

A. COMP is a binary storage format while COMP-3 is packed decimal format.

131.What is COMP-1? COMP-2?

  1. COMP-1 – Single precision floating point. Uses 4 bytes.

COMP-2 – Double precision floating point. Uses 8 bytes.

132.How do you define a variable of COMP-1? COMP-2?

A. No picture clause to be given. Example 01 WS-VAR USAGE COMP-1.

133.How many bytes does a S9(7) COMP-3 field occupy ?

A. Will take 4 bytes. Sign is stored as hex value in the last nibble.

General formula is INT((n/2) + 1)), where n=7 in this example.

134.How many bytes does a S9(7) SIGN TRAILING SEPARATE field occupy ?

A. Will occupy 8 bytes (one extra byte for sign).

135.What is the maximum size of a 01 level item in COBOL I? in COBOL II?

  1. In COBOL II: 16777215

136.What is COMP SYNC?

A. Causes the item to be aligned on natural boundaries. Can be SYNCHRONIZED LEFT or RIGHT.

For binary data items, the address resolution is faster if they are located at word boundaries in the memory. For example, on main frame the memory word size is 4 bytes. This means that each word will start from an address divisible by 4. If my first variable is x(3) and next one is s9(4) comp, then if you do not specify the SYNC clause, S9(4) COMP will start from byte 3 ( assuming that it starts from 0 ). If you specify SYNC, then the binary data item will start from address 4. You might see some wastage of memory, but the access to this comp field is faster.

137.How do you reference the following file formats from COBOL programs?

  1. Fixed Block File – Use ORGANISATION IS SEQUENTIAL. Use RECORDING MODE IS F, BLOCK CONTAINS 0.
  2. Fixed Unblocked – Use ORGANISATION IS SEQUENTIAL. Use RECORDING MODE IS F, do not use BLOCK CONTAINS.
  3. Variable Block File – Use ORGANISATION IS SEQUENTIAL. Use RECORDING MODE IS V, BLOCK CONTAINS 0. Do not code the 4 bytes for record length in FD. i.e. JCL record length will be max record length in program + 4
  4. Variable Unblocked – Use ORGANISATION IS SEQUENTIAL. Use RECORDING MODE IS V, do not use BLOCK CONTAINS. Do not code 4 bytes for record length in FD ie JCL rec length will be max rec length in pgm + 4.
  5. ESDS VSAM file – Use ORGANISATION IS SEQUENTIAL.
  6. KSDS VSAM file – Use ORGANISATION IS INDEXED, RECORD KEY IS, Alternate Record Key Is
  7. RRDS File – Use ORGANISATION IS RELATIVE, RELATIVE KEY IS
  8. Printer File – Use ORGANISATION IS SEQUENTIAL. Use RECORDING MODE IS F, BLOCK CONTAINS 0. (Use RECFM=FBA in JCL DCB).

138.What are different file OPEN modes available in COBOL? In which modes are the files Opened to write.

A. Different Open modes for files are INPUT, OUTPUT, I-O and EXTEND. Of which Output and Extend modes are used to write new records into a file.

139.In the JCL, how do you define the files referred to in a subroutine?

A. Supply the DD cards just as you would for files referred to in the main program.

140.Can you REWRITE a record in an ESDS file? Can you DELETE a record from it?

A. Can rewrite(record length must be same), but not delete.

141.What is file status 92?

A. Logic error. e.g., a file is opened for input and an attempt is made to write to it.

142.What is file status 39?

A. Mismatch in LRECL or BLOCKSIZE or RECFM between your COBOL pgm & the JCL (or the dataset label). You will get file status 39 on an OPEN.

143.What is Static, Dynamic linking ?

A. In static linking, the called subroutine is link-edited into the calling program , while in dynamic linking, the subroutine & the main program will exist as separate load modules. You choose static/dynamic linking by choosing either the DYNAM or NODYNAM link edit option. (Even if you choose NODYNAM, a CALL identifier (as opposed to a CALL literal), will translate to a DYNAMIC call).

A statically called subroutine will not be in its initial state the next time it is called unless you explicitly use INITIAL or you do a CANCEL. A dynamically called routine will always be in its initial state.

144.Explain NEXT and CONTINUE verbs for file handling.

A The Continue verb is used for a situation where there in no EOF condition. i.e. The records are to be accessed again and again in a file. Whereas in the next verb the indexed file is accessed sequentially, whence when index clause is accessed sequentially read next record command is used.

145.What is AMODE(24), AMODE(31), RMODE(24) and RMODE(ANY)? (applicable to only MVS/ESA).

A. These are compile/link edit options. AMODE – Addressing mode. RMODE – Residency mode.

AMODE(24) – 24 bit addressing. AMODE(31) – 31 bit addressing. AMODE(ANY) – Either 24 bit or 31 bit addressing depending on RMODE. RMODE(24) – Resides in virtual storage below 16 Meg line. Use this for 31 bit programs that call 24 bit programs. (OS/VS Cobol pgms use 24 bit addresses only). RMODE(ANY) – Can reside above or below 16 Meg line.

146.What compiler option would you use for dynamic linking?

  1. DYNAM.

147.What is SSRANGE, NOSSRANGE ?

A. These are compiler options w.r.t subscript out of range checking. NOSSRANGE is the default and if chosen, no run time error will be flagged if your index or subscript goes out of the permissible range.

148.How do you set a return code to the JCL from a COBOL program?

A. Move a value to RETURN-CODE register. RETURN-CODE should not be declared in your program.

149.How can you submit a job from COBOL programs?

A. Write JCL cards to a dataset with

//xxxxxxx SYSOUT=(A,INTRDR) where ‘A’ is output class, and dataset should be opened for output in the program. Define a 80 byte record layout for the file.

150.What are the differences between OS VS COBOL and VS COBOL II?

  • OS/VS Cobol pgms can only run in 24 bit addressing mode, VS Cobol II pgms can run either in 24 bit or 31 bit addressing modes allowing program to address above 16 Meg main storage line.
  • Report writer is supported only in OS/VS Cobol.
  • USAGE IS POINTER is supported only in VS COBOL II.
  • Reference modification eg: WS-VAR(1:2) is supported only in VS COBOL II.
  • COBOL II introduces new features (EVALUATE, SET … TO TRUE, CALL … BY CONTEXT, etc)
  • Scope terminators are supported in COBOL II.
  • OS/VS Cobol follows ANSI 74 stds while VS COBOL II follows ANSI 85 stds.
  • Under CICS Calls between VS COBOL II programs are supported.
  • COBOL II supports structured programming by using in-line PERFORM ’s.
  • COBOL II does not support old features (READY TRACE, REPORT-WRITER, ISAM, etc.).
  • In non-CICS environment, it is possible. In CICS, this is not possible.

NTLM Authentication

Tuesday, March 24th, 2009

Introduction:

This BOK details how to get a Java-based web-application to negotiate with a IE web client for username and domain information. This is a common requirement for web-based applications especially ones that do not want to bore users with a login page. IE will negotiate a user’s password hashes with the webserver, which checks their authenticity against a windows domain controller. If valid, the user’s username and domain will be accessible to the webserver servlets.

NTLM Authentication and how we achieve it:

 
The method HttpServletRequest.getRemoteUser() should return the username of the person using the browser which fired a request to this Servlet.
This method, however works correctly only if the user has been authenticated first by a webserver authentication scheme -
which could be BASIC,DIGEST or CLIENT-CERT. This is the kind of setup the the Apache webserver provides, giving a challenge-response, username-password method of authentication.

What we do here is use a Servlet filter provided as part of the open-source jCIFS package, to get an IE user's username and domain. 

This filter will take the trouble of intercepting user requests, asking IE for the user's password hashes,validating them against a windows domain controller and enabling HttpServletRequest.getRemoteUser() to return the windows user id.
 
Please note this method will not work for non-IE clients, simply because this is a proprietary extension by Microsoft. 
 
For other browsers you will have to rely on BASIC or certificate-based authentication.

How to setup your web application:

 First, we need to download a jcifs jar from http://jcifs.samba.org. I have tested this with jcifs version 0.7.14.jCIFS is from the makers of Samba and provides APIs to access Windows shares, networks and the ability to authenticate against a Windows domain controller. Place this jar under WEB-INF/lib of your web application. There is a filter called jcifs.http.NtlmHttpFilter which implements all the wizadry above. You need to register it in your application's web.xml descriptor:
 
<web-app>
...
    <!-- NTLM HTTP Authentication only works with MSIE -->
    
    <filter>
        <filter-name>NTLM HTTP Authentication Filter</filter-name>
        <filter-class>jcifs.http.NtlmHttpFilter</filter-class>

        <!-- CCD will help you with a PDC and WINS server ip at your location. -->
        <init-param>
            <param-name>jcifs.http.domainController</param-name>
            <param-value>192.168.170.5</param-value>
        </init-param>

        <init-param>
            <param-name>jcifs.netbios.wins</param-name>
            <param-value>192.168.166.13</param-value>
        </init-param>
    </filter>

    <!-- This is the url under which we need access to the username and domain. -->

    <filter-mapping>
        <filter-name>NTLM HTTP Authentication Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

...

</web-app>
 
That's it. Now all IE requests to your webserver urls as specified in the web.xml entries are negotiated so that you can call a HttpServletRequest.getRemoteUser() to get the remote user's username in the form.

            DOMAIN\username.

Please note at no point will a password dialog pop up for the user, the password hashes are picked from IE and validated with the domain controller.
 
 
Example code for a servlet :
 
 
public void doGet( HttpServletRequest req,
                        HttpServletResponse resp )
throws IOException, ServletException
        
        {

PrintWriter out = resp.getWriter();

resp.setContentType( “text/html” );
out.println( “<HTML><HEAD><TITLE>NTLM HTTP Authentication Example</TITLE></HEAD><BODY>” );
out.println( “<h2>NTLM HTTP Authentication Example</h2>” );

out.println( req.getRemoteUser() + ” logged in” );

 

}

If the filter has not been configured properly, a null will be printed for the above call to req.getRemoteUser().

 

References:

  • Web Link :- http://jcifs.samba.org.

Jsp – Oracle Connectivity

Monday, March 23rd, 2009

Introduction

This document deals with the JSP connectivity with Oracle.This also exemplifies adding,updating, deleting and retrieving records from database(Oracle) through JSP.

Prerequisites

  • Tomcat Server.
  • Oracle Client.
  • Oracle Server.

Target Readers : All

Getting Started

Copy a jar file class12.jar from Oralce_root->jdbc->lib->class12.jar
to Tomcat Server in Tomcat_root->common->lib.

Database Connectivity

<%
try{
Class.forName(”oracle.jdbc.driver.OracleDriver”).newInstance();

//Creating the connection object
Connection con = DriverManager.getConnection(”jdbc:oracle:thin:” + “@172.24.205.62:1521:infosys”,”Uname”,”Pwd”);

con.close();
}
catch (SQLException sqle){
throw new SQLException();
}
%>

Note:

172.24.205.62 -> IP Address of Oracle Server.
1521 -> Port Number.
infosys -> Host String.
Uname -> UserName.
Pwd -> Password.

Adding a Record

<%
try{
Class.forName(”oracle.jdbc.driver.OracleDriver”).newInstance();

//Creating the connection object
Connection con = DriverManager.getConnection(”jdbc:oracle:thin:” + “@172.24.205.62:1521:infosys”,”Uname”,”Pwd”);

PreparedStatement stmt = con.prepareStatement(”insert into Table_Name values(?,?,?)”);
stmt.setString(1,column1);
stmt.setInt(2,column2);
stmt.setString(3,column3);

stmt.executeUpdate();

con.close();
}
catch (SQLException sqle){
throw new SQLException();
}
%>

Where column1,column2,column3 can be static values or can be taken from the previous page by establishing session.

Deleting a Record

<%
try{
Class.forName(”oracle.jdbc.driver.OracleDriver”).newInstance();

//Creating the connection object
Connection con = DriverManager.getConnection(”jdbc:oracle:thin:” + “@172.24.205.62:1521:infosys”,”Uname”,”Pwd”);

PreparedStatement stmt = con.prepareStatement(”delete from Table_Name where EmpName=’XYZ’”);
stmt.executeUpdate();

con.close();
}
catch (SQLException sqle){
throw new SQLException();
}
%>

Updating a Record

<%
try{
Class.forName(”oracle.jdbc.driver.OracleDriver”).newInstance();

//Creating the connection object
Connection con = DriverManager.getConnection(”jdbc:oracle:thin:” + “@172.24.205.62:1521:infosys”,”Uname”,”Pwd”);

PreparedStatement stmt = con.prepareStatement(”update Table_Name set Designation=’Software Engineer’ where EmpName=’XYZ’”);
stmt.executeUpdate();

con.close();
}
catch (SQLException sqle){
throw new SQLException();
}
%>

Retrieving a Record

<%
String empName=”";
int empNumber=0;
String empDesignation=”";

try{
Class.forName(”oracle.jdbc.driver.OracleDriver”).newInstance();

//Creating the connection object
Connection con = DriverManager.getConnection(”jdbc:oracle:thin:” + “@172.24.205.62:1521:infosys”,”Uname”,”Pwd”);

PreparedStatement stmt = con.prepareStatement(”select * from Table_Name”);
ResultSet rs = stmt.executeQuery();

while(rs.next())
{
empName = rs.getString(”EMPNAME”);
empNumber = rs.getInt(”EMPNO”);
empDesignation = rs.getString(”DESIGNATION”);

out.println(empName);
out.println(empNumber);
out.println(empDesignation);
}

con.close();
}
catch (SQLException sqle){
throw new SQLException();
}
%>

JSP FAQ

Wednesday, March 11th, 2009


TABLE OF CONTENTS

How do I communicate with a JSP page from an applet?

How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts?

What’s the difference between the JSDK and the JSWDK? And what’s the current version?

How can I get to print the stacktrace for an exception occuring within my JSP page?

Can I invoke a JSP error page from a servlet?

How can I send email from a JSP page?

How do I use a scriptlet to initialize a newly instantiated bean?

Can you make use of a ServletOutputStream object from within a JSP page?

How can I enable session tracking for JSP pages if the browser has disabled cookies?

How can I declare methods within my JSP page?

Can I stop JSP execution while in the midst of processing a request?

Is there a way I can set the inactivity lease period on a per-session basis?

How can I get to view any compilation/parsing errors at the client while developing JSP pages?

How can I delete a cookie from within a JSP page?

How do I set a cookie within a JSP page?

Can a JSP page instantiate a serialized bean?

Is there a way to reference the “this” variable within a JSP page?

Can JSPs and servlets share the same session?

Show me an example of POST request chaining using JSPs and servlets

How does a servlet communicate with a JSP page?

JSP 0.91 and 0.92 specifications are no longer available at java.sun.com. Is there somewhere else I can download them?

Where can I find the complete list of commercial vendor support for JSP?

Are there any JSP engines which support JavaScript?

How does the “application” scope work with the useBean tag?

My JSP file compiles just fine…but I always get a NoClassDefFoundError when I try to access a bean via the useBean tag. Why?

How can I implement a thread-safe JSP page?

Can a JSP page process HTML FORM data?

How does JSP handle run-time exceptions?

What JSP lifecycle methods can I override?

How can I override the jspInit() and jspDestroy() methods within a JSP page?

How do I include static files within a JSP page?

How do I use comments within a JSP page?

How do I perform browser redirection from a JSP page?

How do I prevent the output of my JSP pages from being cached by the browser?


 

 

 

How do I communicate with a JSP page from an applet?

 

It’s similar to communication between Servlet and Applet. I’m also suffering for that. In applet, there is no problem when posting a request to JSP. But in case of getting a response of JSP, “java.io.StreamCorruptedException” occurs if I use ObjectInputStream. It’s fine, however, if I use InputStreamReader. Confer the sample below.

 

/** applet */

   :

// Get URLConnection

String urlStr = “http://www.webtrack.co.kr/jsp/appletproxy.jsp”;

URL serverURL = new URL(urlStr);

URLConnection uc = serverURL.openConnection();

uc.setDoOutput(true); // intends to write data to the URL connection

uc.setUseCaches(false); // the protocol must always try to get a fresh copy of the object

uc.setRequestProperty(”Content-type”, “application/octet-stream”);

// Request(POST)

ObjectOutputStream objOut = new ObjectOutputStream(uc.getOutputStream());

objOut.writeObject(new String(”Hello, acidzazz?”));

objOut.flush();

objOut.close();

// Get Server’s response

ObjectInputStream objIn = new ObjectInputStream(uc.getInputStream());

BufferedReader ir = new BufferedReader(new InputStreamReader(uc.getInputStream()));

String s = “”;

while( (s = ir.readLine()) != null )

     System.out.println(s);

ir.close();

   :

/** JSP */

   :

<%

// Get Request(POST) of applet

ObjectInputStream objIn = new ObjectInputStream(request.getInputStream());

userID = (String)objIn.readObject();

objIn.close();

// Response to Applet

response.setContentType(”application/octet-stream”);

ObjectOutputStream objOut = new ObjectOutputStream(response.getOutputStream());

objOut.writeObject(new String(”Hello, applet”);

objOut.flush();

objOut.close();

   :

%>

 

How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts?
 

The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP page is accessed for the very first time. This is because the JSP page undergoes a “translation phase” wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic – it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources.

Subsequent client requests to the JSP page does not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet’s service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.)

There have been some recent studies contrasting the performance of servlets with Perl scripts running in a “real-life” environment. The results are favorable to servlets, especially when they are running in a clustered environment. For details, see:

http://www.objexcel.com/workingjava.htm#Web Server Benchmarks

 

What’s the difference between the JSDK and the JSWDK? And what’s the current version?

 

The kit for developing servlets, containing the Servlet API classes and tools, used to be called the Java Servlet Development Kit (JSDK). Then Sun renamed the Java Development Kit (JDK) to the Java 2 Software Development Kit (J2SDK). Since J2SDK sounds a lot like JSDK, the Servlet team renamed JSDK to JavaServer Web Development Kit (JSWDK). (They also added support for JSPs.)

Here’s where it gets confusing. When they renamed it, they also renumbered it. So the JSWDK 1.0 is actually more recent than the JSDK 2.1. It’s also confusing that when people want to develop servlets, they have to download something called a JavaServer Web Development Kit, which sounds like it should be used to develop servers, not servlets.

A further confusion is that the Servlet spec is developed independently from the JSP spec, and they both have different versions than the JSDK/JSWDK.

The following table summarizes the confusion.

Product

Version

Servlet spec

JSP spec

Tomcat

3.0

2.2

1.1

JSWDK

1.0.1

2.1

1.0.1

JSDK

2.1

2.1

none

JSDK

2.0

2.0

none

Make sure you look for the “W”!

 

How can I get to print the stacktrace for an exception occuring within my JSP page?

 

By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method.

However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:

<%@ page isErrorPage=”true” %>

<%

out.println(”<pre>”);

PrintWriter pw = response.getWriter();

exception.printStackTrace(pw);

out.println(”</pre>”);

%>

 

Can I invoke a JSP error page from a servlet?

 

Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:

java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained

The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:

protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e)

   throws ServletException, IOException {

    request.setAttribute (”javax.servlet.jsp.jspException”, e);

    getServletConfig().getServletContext().getRequestDispatcher(errorPageURL).forward(request, response);

}

 

public void doPost(HttpServletRequest request, HttpServletResponse response) {

 try {

 // do something

 } catch (Exception ex) {

  try {

   sendErrorRedirect(request,response,”/jsp/MyErrorPage.jsp”,ex);

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

}

 

How can I send email from a JSP page?

 

You can send email from any JSP engine (like the JSWDK reference implementation) that supports the Sun specific sun.net.smtp package.

(Statutory warning: Using internal Sun-specific packages is not an approach jGuru recommends, as it will prevent your JSP pages from being truly portable.)

The following scriptlet makes use of the SmtpClient class to send an email from within a JSP page.

<%@ page import=”sun.net.smtp.SmtpClient, java.io.*” %>

<%

 String from=”gseshadri@hotmail.com”;

 String to=”govind@jguru.com, govi@bigfoot.com”;

 try{

     SmtpClient client = new SmtpClient(”mail.perspex.com”);

     client.from(from);

     client.to(to);

     PrintStream message = client.startMessage();

     message.println(”To: ” + to);

     message.println(”Subject:  Sending email from JSP!”);

     message.println(”This was sent from a JSP page!”);

     message.println();

     message.println(”Cool beans! :-) ”);

     message.println();

     message.println(”Govind Seshadri”);

     message.println(”jGuru.com”);

     message.println();

     client.closeServer();

  }

  catch (IOException e){    

     System.out.println(”ERROR SENDING EMAIL:”+e);

  }

%>

 

How do I use a scriptlet to initialize a newly instantiated bean?

 

A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

<jsp:useBean id=”foo” class=”com.Bar.Foo” >

  <jsp:setProperty name=”foo” property=”today” value=”<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())

%>”/>

<%– scriptlets calling bean setter methods go here –%>

</jsp:useBean >

 

Can you make use of a ServletOutputStream object from within a JSP page?

 

No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.

A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:

<%@ page buffer=”none” %>

 

How can I enable session tracking for JSP pages if the browser has disabled cookies?

 

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting.

URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response.

Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object.

Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages.

Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.

hello1.jsp

<%@ page session=”true” %>

<%

  Integer num = new Integer(100);

  session.putValue(”num”,num);

 String url =response.encodeURL(”hello2.jsp”);

%>

<a href=’<%=url%>’>hello2.jsp</a>

hello2.jsp

<%@ page session=”true” %>

<%

  Integer i= (Integer )session.getValue(”num”);

  out.println(”Num value in session is “+i.intValue());

%>

 

What’s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?

 

Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.

Also, note that SingleThreadModel is pretty resource intensive from the server’s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free – which results in poor performance. Since the usuage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

 

How can I declare methods within my JSP page?

 

You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions.

Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:

<%!

      public String whereFrom(HttpServletRequest req) {

      HttpSession ses = req.getSession();

     

      return req.getRemoteHost();

     }

%>

<%

     out.print(”Hi there, I see that you are coming in from  “);

%>

<%= whereFrom(request) %>

 

Can I stop JSP execution while in the midst of processing a request?

 

Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing.

For example, consider:

<%

      if (request.getParameter(”foo”) != null) {

          // generate some html or update bean property

      } else {

 

      /* output some error message or provide redirection

          back to the input form after creating a memento

          bean updated with the ‘valid’ form elements that were input.

          this bean can now be used by the previous form to initialize

          the input elements that were valid

          then, return from the body of the _jspService() method to

          terminate further processing   */

 

          return;

      }

%>

 

Is there a way I can set the inactivity lease period on a per-session basis?

 

Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file.

However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:

<%

    session.setMaxInactiveInterval(300);

%>

would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

 

How can I get to view any compilation/parsing errors at the client while developing JSP pages?

 

With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:

jsp.initparams=sendErrToClient=true

This will cause any compilation/parsing errors to be sent as part of the response to the client.

 

How can I delete a cookie from within a JSP page?

 

A cookie, mycookie, can be deleted using the following scriptlet:

<%

     Cookie killMyCookie = new Cookie(”mycookie”, null);

     killMyCookie.setMaxAge(0);

     killMyCookie.setPath(”/”);

     response.addCookie(killMyCookie);

%>

 

How do I set a cookie within a JSP page?

 

Setting cookies from within a JSP page is similar to the way they are done within servlets. For example, the following scriptlet sets a cookie “mycookie” at the client:

<%

       Cookie mycookie = new Cookie(”aName”,”aValue”);

       response.addCookie(mycookie);

 %>

Typically, cookies are set at the beginning of a JSP page, as they are sent out as part of the HTTP headers.

 

Can a JSP page instantiate a serialized bean?

 

No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:

<jsp:useBean id=”shop”  type=”shopping.CD” beanName=”CD”  />

<jsp:getProperty name=”shop” property=”album” />

A couple of important points to note. Although you would have to name your serialized file “filename.ser”, you only indicate “filename” as the value for the beanName attribute.

Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

 

Is there a way to reference the “this” variable within a JSP page?

 

Yes, there is. Under JSP 1.0, the page implicit object is equivalent to “this”, and returns a reference to the servlet generated by the JSP page.

 

With Sun’s JSWDK 1.0, I can access only the class file for the servlet generated from my JSP page. Is there a way to see the Java source for the generated servlets?

 

For Sun’s JSWDK 1.0, set the initialization parameter:

jsp.initparams=keepgenerated=true

This can be found within the web-inf/servlets.properties file for your application.

When this is passed to your JSP servlet, it will preserve the Java source along with the class file in the work subdirectory for the engine.

 

Can JSPs and servlets share the same session?

 

Yes, of course. Remember, JSPs are always translated into their servlet equivalent before they are initialized and ready to process incoming requests. JSP pages are also provided with the session implicit object which allows them to completely manage the session, including its creation and invalidation.

Any bean or object placed by the JSP page into the session can be later used by any other servlet or JSP page belonging to the same session.

 

Show me an example of POST request chaining using JSPs and servlets

 

The following code example demonstrates how request chaining can be implemented using a combination of JSPs and servlets.

Consider the following JSP page, say Bean1.jsp, which essentially instantiates the bean fBean, places it in the request, and forwards the call to the servlet JSP2Servlet. Observe the way the bean is instantiated – here we automatically call the bean’s setter methods for properties which match the names of the posted form elements, while passing the corrosponding values to the methods.

<html>

<body>

<jsp:useBean id=”fBean” class=”govi.FormBean” scope=”request”/>

<jsp:setProperty name=”fBean” property=”*” />

<jsp:forward page=”/servlet/JSP2Servlet” />

</body>

</html>

The servlet JSP2Servlet now extracts the bean passed to it from the request, makes changes using the appropriate setters, and forwards the call to another JSP page Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller, can also place additional beans if necessary, within the request.

public void doPost (HttpServletRequest request,

       HttpServletResponse response) {

 

try {

    FormBean f = (FormBean) request.getAttribute (”fBean”);

    f.setName(”Mogambo”);

    // do whatever else necessary

   getServletConfig().getServletContext().

         getRequestDispatcher(”/jsp/Bean2.jsp”).

             forward(request, response);

     } catch (Exception ex) {

             . . .

     }

}

The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that may have been passed by the controller servlet) from the request and extract its properties.

<html>

<body>

Within JSP2

<P>

<jsp:useBean id=”fBean” class=”govi.FormBean” scope=”request”/>

<jsp:getProperty name=”fBean” property=”name” />

</body>

</html>

 

How does a servlet communicate with a JSP page?

 

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request,

                    HttpServletResponse response) {

 

     try {

           govi.FormBean f = new govi.FormBean();

              String id = request.getParameter(”id”);

           f.setName(request.getParameter(”name”));

           f.setAddr(request.getParameter(”addr”));

           f.setAge(request.getParameter(”age”));

              //use the id to compute         

              //additional bean properties like info

              //maybe perform a db query, etc.

              // . . .

              f.setPersonalizationInfo(info);

           request.setAttribute(”fBean”,f);

           getServletConfig().getServletContext().getRequestDispatcher

                           (”/jsp/Bean1.jsp”).forward(request, response);

     } catch (Exception ex) {

                . . .

     }

 }

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.

<jsp:useBean id=”fBean” class=”govi.FormBean” scope=”request”/>

<jsp:getProperty name=”fBean” property=”name” />

<jsp:getProperty name=”fBean” property=”addr” />

<jsp:getProperty name=”fBean” property=”age” />

<jsp:getProperty name=”fBean” property=”personalizationInfo” />

 

 

JSP 0.91 and 0.92 specifications are no longer available at java.sun.com. Is there somewhere else I can download them?

 

Yes. You can download JSP 0.91 specification at http://www.kirkdorffer.com/jspspecs/jsp091.html.

JSP 0.92 specification can be downloaded from http://www.kirkdorffer.com/jspspecs/jsp092.html

 

Where can I find the complete list of commercial vendor support for JSP?

 

Daniel Kirkdorffer maintains a regularly updated list of products which support the JSP API. You can access it at http://www.interpasnet.com/JSS/textes/jsp2.htm.

 

Are there any JSP engines which support JavaScript?

 

Yes. Resin 1.0 from Caucho Technologies supports both Java and JavaScript for scripting and implements JSP 1.0.

PolyJSP from Plenix supports Java, JavaScript and WebL for scripting, and implements JSP 0.92.

 

How does the “application” scope work with the useBean tag?

 

Consider the following example:

<useBean id=”counter” class=”foo.Counter” scope=”application” />

In this example, when the Counter bean is instantiated, it is placed within the servlet context, and can be accessed by any JSP or servlet that belong to the application (i.e. belongs to the same servlet context).

The servlet equivalent of the above useBean action is:

getServletContext().setAttribute(”counter”, new foo.Counter());

If the bean was previously created by another JSP or servlet and was placed within the application (servlet) context, the useBean action would then serve to retrieve the object.

The servlet equivalent of retrieving a bean from the application context is:

foo.Counter ctr = (foo.Counter) getServletContext().getAttribute(”counter”);

 

My JSP file compiles just fine…but I always get a NoClassDefFoundError when I try to access a bean via the useBean tag. Why?

 

Make sure your beans belong to a package, and that you are fully qualifying the bean when indicating the value for the class attribute. For example, if your bean abc.class belongs to the package foo, make sure you indicate the value for the class attribute as:

<useBean id=”mybean” class=”foo.abc” scope=”session” />

and not as:

<useBean id=”mybean” class=”abc” scope=”session” />

 

How can I implement a thread-safe JSP page?

 

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface.

This is done by adding the directive

<%@ page isThreadSafe=”false” %>

within your JSP page.

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

 

Can a JSP page process HTML FORM data?

 

Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:

<%

String item = request.getParameter(”item”);

int howMany = new Integer(request.getParameter(”units”))

                                            .intValue();

%>

or

<%= request.getParameter(”item”) %>

 

 

How does JSP handle run-time exceptions?

 

You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:

<%@ page errorPage=”error.jsp” %>

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.

Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage=”true” %>

the Throwable object describing the exception may be accessed within the error page via the exception implicit object.

Note: You must always use a relative URL as the value for the errorPage attribute.

 

What JSP lifecycle methods can I override?

 

You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

 

How can I override the jspInit() and jspDestroy() methods within a JSP page?

 

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

<%!

     public void jspInit() {

             . . .

     }

%>

 

<%!

public void jspDestroy() {

             . . .  

     }

%>

 

How do I include static files within a JSP page?

 

Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:

<%@ include file=”copyright.html” %>

Do note that you should always supply a relative URL for the file attribute.

Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

 

How do I use comments within a JSP page?

 

You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client.

For example:

<%– the scriptlet is now commented out

  <%

     out.println(”Hello World”);

  %>

–%>

You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

<!– (c)1999 jGuru.com –>

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

<%

//some comment

 

/**

yet another comment

**/

%>

 

 

How do I perform browser redirection from a JSP page?

 

You can use the response implicit object to redirect the browser to a different resource, as:

response.sendRedirect(”http://www.foo.com/path/error.html”);

You can also physically alter the Location HTTP header attribute, as shown below:

<%

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

String newLocn = “/newpath/index.html”;

response.setHeader(”Location”,newLocn);

%>

How do I prevent the output of my JSP pages from being cached by the browser?

 

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser.

Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

<%

response.setHeader(”Cache-Control”,”no-store”); //HTTP 1.1

response.setHeader(”Pragma”,”no-cache”); //HTTP 1.0

response.setDateHeader (”Expires”, 0); //prevents caching at the proxy server %>