Posts Tagged ‘Web applications’

WebSphere 3.5 – Frequently Asked Questions

Wednesday, March 25th, 2009

Table of Contents

1. How do I install WebSphere Application Server when logged on to a Windows NT domain?
2. While starting WS Admin Server from control panel, the error comes which says “Service Code 10 error, unable to start the service”. What is it and how to solve it?

 

3. For Developing Beans and Servlets what changes should I make in my System Classpath?

 

4. While Deploying a bean, WebSphere provide 2 options “Deploy only” and “Deploy and Workload Manage”. What are these and which one should I use?

 

5. My class gets compiled perfectly but when I try to deploy it on WebSphere it gives NoClassDefFoundError? Whats the reason?

 

6. Where can I find my System.out.println() or System.err.println() statements written in my bean?

 

7. I want to connect to Oracle Database. How to do that?

 

8. How to install a JDBC Driver and configure a DataSource with a SINGLE GUI?

 

9. How to look up DataSource?

 

10. What care should I take while running a java client to access the beans?

 

11. I am getting ClassCastException while running a java client. What is the reason?

 

12. I have changed the business logic in my Bean. Does this mean that I have to redeploy the bean?

 

13. Deployment of my bean fails. In the stack trace, the last line it shows is “Veriying EJBs……”?

 

14. Is it possible to precompile JSPs for WebSphere Application Server?

 

15. How to monitor the performance of the WebSphere?

 

 

1. How do I install WebSphere Application Server when logged on to a Windows NT domain?

If you log on with a domain user account and try to install WAS, make sure:

 

Ø You are added into the local administrator group (YOURDOMAIN/YOURUSERNAME must be in the member list of the local administrator group). If not, the installation will stop and say you are not allowed to install.

Ø Your username is also a local user account on the computer you are using.

Ø Your local user account is a member of the administrator group.

Ø Your local account password matches the domain account password.

 

If you do not have a local account, installation continues but you might not see any services. If your passwords don’t match, you can still install but your services might fail, because each service uses the domain password to start the service and validate the password against the local machine.
2. While starting WS Admin Server from control panel, the error comes which says “Service Code 10 error, unable to start the service”. What is it and how to solve it?

 

This error implies that Windows is unable to start this particular service, may be because there is some configuration failure in the internal files that windows read while starting the service or there can be many more reasons.

To debug the reason of the error see the “tracefile” which the server creates. Its in <WAS_HOME>/logs/tracefile. (Where WAS_HOME is the path where your bin, logs and other such folders lie, Ex. C:/WebSphere/AppServer)

 

Moreover, one can try to start the server from command prompt.

Go to <WAS_HOME>/bin/debug and start adminserver.bat. This internally sets all the paths required for running the server and then starts the server and hence the chances of failure are less. It also provides messages on command prompt and one can find the reason for failure.

 

From my practical experience I have noticed that whenever there are some changes made in “admin.config” file which lies in <WAS_HOME>/bin directory, this error crops up. Presently there is absolutely no need of changing your admin.config file. Without changing it we can meet our objective. Its explained in detail in the fifth question.
3. For Developing Beans and Servlets what changes should I make in my System Classpath?

Make sure that you are using JDK given by the WebSphere.

For developing beans and servlets , apart from adding jars that are provided with JDK of WebSphere , add

<WAS_HOME>/lib/ujc.jar; <WAS_HOME>/lib/ejs.jar; <WAS_HOME>/lib/servlet.jar;<WAS_HOME>/jdk/jre/lib/ext/iioprt.jar

 

4. While Deploying a bean, WebSphere provide 2 options “Deploy only” and “Deploy and Workload Manage”. What are these and which one should I use?
As far as deploying is concerned both are same.

Workload Management is used when you are using multiple servers and are expecting a huge load on your server. In this scenario it becomes important that your request gets distributed between different servers so that the load can be balanced and resources of the server can be properly utilized.

 

5. My class gets compiled perfectly but when I try to deploy it on WebSphere it gives NoClassDefFoundError? What’s the reason?

WebSphere manages its OWN CLASSPATH. So it will not look into your system classpath to find out for a particular class.

In the Administrator console, when you click on Default_server, then on right hand side you can see a text box with subject as “Command Line Arguments”. This is where you can set your classpath.

Type

-classpath <path of your jar>

If more than 1 jar is there, then use “;(semi-colon)” as a separator.

Ex. -classpath c:/MyJars/ABC.jar;c:/MyJars/BCD.jar
Click Apply and then restart the default server. The changes will be reflected soon after.

Make sure that there is no space after semi-colon.

This is the path that will be searched first by the Application server for a particular class.

Make sure that you keep jars of only helper classes in this path.

Doing this you can avoid changing admin.config every time and hence would not need to restart the AdminServer.
6. Where can I find my System.out.println() or System.err.println() statements written in my bean?

 

If you are using Default Server, then

System.out.println() statements can be found out in <WAS_HOME>/logs/default_server_stdout.log file

System.err.println()statements can be found out in <WAS_HOME>/logs/default_server_stderr.log file.

 

7. I want to connect to Oracle Database. How to do that?
To connect to oracle database first you include “Classes12.zip” in your Application Classpath(how to add a jar/zip to application classpath has been discussed in question 5) as it provides the thin driver “oracle.jdbc.driver.OracleDriver” which is used by java to connect to Oracle. Now Restart the server.

 

Add the following code in your java program-

 

import oracle.jdbc.driver.OracleDriver;

 

public Connection getConnection();

{

try

{

DriverManager.registerDriver(new OracleDriver());

String url = “jdbc:oracle:thin:@<hostname>:<portno>:<sid>”;

 

//where

//hostname is the name where the Oracle Server is installed.

//portno is the port no on which oracle listens, (by default Oracle listens on 1521)

//sid is the database name

 

Connection con = DriverManager.getConnection(url,<user_name>,<password>);

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

return con;

}

 

8. How to install a JDBC Driver and configure a DataSource with a SINGLE GUI?

Click the “Console” on the Menu bar , then click “Tasks”, then click “Create Data Source”.

It will give you 2 options. Choose the option that says “Create and Install new JDBC Driver”.

Follow the steps that are similar to creating a JDBC driver and after that it will give the GUI that asks for the DataSource name and the Database name.

Complete it and click the finish button.

Hence installing a driver and configuring a DataSource will be done in a single procedure.

 

9. How to look up DataSource?
Suppose the name of the Datasource given by you is “mysource”.

Then while looking it up use “jdbc/mysource”;

 

E.g.

InitialContext ic = new InitialContext();

DataSource ds = (DataSource)ic.lookup(”jdbc/mysource”);

 

The Java object retrieved is a DataSource object stored in the “jdbc” context with the logical name of “mysource.”

 

10. What care should I take while running a java client to access the beans?

Make sure you are using the jdk that’s shipped with WebSphere. Set the path parameter of your System to <WAS_HOME>/jdk/bin.

Make your Classpath settings for jars in <WAS_HOME>/jdk/jre/lib and for

Jars in <WAS_HOME>/jdk/jre/lib/ext directory.

Make sure that you have added the DeployedJar in your System Classpath as it contains Stubs which the client will be using to communicate with beans else you will get ClassCastException.

Even after doing this if you get any NoClassDefFoundError then try setting the System classpath for the jars that are present in the <WAS_HOME>/lib directory.

 

11. I am getting ClassCastException while running a java client. What is the reason?
Refer to previous question.

 

12. I have changed the business logic in my Bean. Does this mean that I have to redeploy the bean?
NO. Deployment in no manner is concerned with the business logic of your bean.

 

Hence if you want the new changes to get reflected in the bean do the following steps -

 

v Recompile your bean with the changes.

v Copy the compiled class and paste it into a folder which represents its package hierarchy under the C:\ drive(or any other drive)

E.g. Suppose your class name is com.bgc.nps.ABC.class.

And this class when seen in the explorer lies in c:\MyFolder\Project\com\bgc\nps\ABC.class
If this is the case then make a hierarchy in your “C:\” drive and place the ABC.class in this package.

So your new class when seen in explorer will lie in

C:\com\bgc\nps\ABC.class.

v Stop the default server

v Open DeployedJar of your bean in the WinZip.

v Check the checkbox which says “Save extra folder info”

v Click on “Add” and browse for your bean class (i.e. ABC.class) under new path.

v Add it to the zip

v Restart the Default Server.
13. Deployment of my bean fails. In the stack trace, the last line it shows is “Verifying EJBs……”?
Failure at this step means that the method signature in the REMOTE interface DOES NOT match with that in your implementation (i.e. Bean) class.

 

E.g. If in Remote interface you declare a function as

public String myString(String a) throws RemoteException, SQLException;

And in your Implementation Class you write this function as

Public String myString(String a) throws RemoteException

As the declaration and implementation are not identical, hence Deployment will fail.

 

14. Is it possible to precompile JSPs for WebSphere Application Server?

Use the jspbatchcompiler.bat file that ships with WebSphere Application Server. It is located in the <WAS_HOME>\bin directory, and uses a configuration file (batchcompiler.config) to pass in the parameters it needs.

In evaluation copy this facility may NOT be available but its available for licensed copy.

 

15. How to monitor the performance of the WebSphere?
There is a stand-alone tool known as Resource Analyzer. It can monitor performance related issues, such as number of threads spawn, number of connection available in the pool etc. To get the detailed information see the Red Handbook provided by WebSphere.

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

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.

Servlet for Beginners

Tuesday, March 24th, 2009

Servlet for Beginners

 

 

 

 

Introduction

 

Web applications are generally based upon Client Server Architecture in which a client sends a request to the server. Depending upon the request, the server responds to the client providing it the required information. To handle such client requests, server side programs are needed. Here comes the need of servlet .A servlet can be defined as a server side program which offers all the advantages of java which includes platform independency also.

 

Example of client request:

 

One of the most common real life scenarios using client server architecture is: web based mail server. When a user enters his userId and password, he is requesting the server to provide him with his mailbox and all other data. Here user doesn’t invoke any program to do all such task but a server side program or set of server side programs do the entire related task. The client request is mapped to a servlet.

 

A user can never invoke the servlet .Servlets are server invoked programs.

 

Java Servlet API 2.3 is defined in java packages: javax.servlet, javax.servlet.http

The package javax.servlet is generic to all protocols i.e. it is protocol independent while javax.servlet.http is specific to http protocol.

 

Some Basic Terminology to have a better understanding of Servlets:

 

Web Container:  A web container provides run time environment for working of web components. The main task of a web container is life cycle management of all the web components. Also it supports creation of objects for the arguments, security related tasks and concurrency control.

 

 

Life Cycle Of A Servlet

 

Controlling the life cycle of a servlet is the task of the container in which servlet is deployed. The life cycle of a servlet has following phases:

 

Initializing a servlet or Birth of a servlet:

 

When a request is first time mapped to a servlet, the container loads the servlet. Then instance of the servlet is created. Then, to instantiate that instance init () is invoked. The Servlet interface provides declaration of init ().To customize this instantiation process, init () method needs to be overridden. If the instantiation can not be completed successfully, UnavailableException should be thrown by such servlet. This method is invoked by any servlet only once in a life time i.e. when it is being loaded first time. The initialization variables, if any, should be placed in this method.

 

Method signature: public void init(ServletConfig config) throws ServletException

 

Providing service for a servlet:

 

After a servlet instance has been instantiated, it should be able to do the needed task i.e. to handle the client side requests. When a servlet is initialized in an appropriate manner, it means an instance of servlet is available. Now each time the server receives request, a new thread is spawned from the same instance and the service () method is invoked. All the application logic is included in this method. It acts as an entry point. The service () method, by default checks the HTTP header of the request to check whether it needs to call doGet () method or doPost () method .In case, both methods need to be invoked, then any of the methods i.e. doPost () and doGet() can call another one.

 

 

Method signature: public void service (ServletRequest request, ServletResponse

                                                     response) throws ServletException, IOException    

                                                                       

 

Destroying/Finalizing a servlet or Death of servlet:

 

A servlet should be destroyed when its task is over. The container invokes destroy () method for a servlet instance when it determines that the services of this servlet are not needed now. Invocation of destroy () method releases all the memory resources being used by the servlet.A servlet should be removed from memory only after all its service methods have been completed. It is the place for all clean up tasks.

 

Method signature: public void destroy ()

 

Discussing the Basic Interfaces and classes in servlet API:

 

1 Servlet interface

2 GenericServlet class

3 HttpServlet class

4 ServletRequest interface

5 ServletResponse interface

6 HttpServletRequset interface

7 HttpServletResponse interface

 

1.  Servlet interface:  This is the interface which a class should implement to become

     a servlet.The following methods must be implemented while implementing

     javax.servlet.Servlet interface:

 

 

è       public void init(ServletConfig config)

è    public void service(ServletRequest request, ServletResponse response)

è    public void destroy()

è    public ServletConfig getServletConfig()

è    public String getServletInfo()

 

 

2.   GenericServlet class: This is the class to provide basic implementation for Servlet

       interface.

 

      public abstract class GenericServlet implements Servlet, ServletConfig,

      Serializable

       

 

       

       It provides following additional methods:

 

 

è       public init()

è       public void log(String message)

è       public void log(String message, Throwable t)

 

 

3.     HttpServlet class: This is a subclass of GenericServlet class.It provides HTTP

      specific implementation of Servlet interface. Mostly the servlet classes

      extend this class to provide functionality of a servlet.

 

            public abstract class HttpServlet extends GenericServlet implements

            Serializable

 

            Here are the mainly used methods as specified in this class:

 

è    service() methods :

 

      There are two variants of service () methods in HttpServlet class as

      discussed below:

 

public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException

 

 

protected void service (HttpServletRequest request, HttpResponse response) throws ServletException,IOException

 

 

The public service method is implementation of GenericServlet class. Practically the above service methods should not be overridden if only default behavior is needed. In case when additional behavior is required, these methods need to be overridden including the default behavior using super.service().

 

When the container receives a new request, it invokes the methods in following sequence:

 

a)    Firstly, the public service () method is invoked.

 

b)    The arguments are casted to HttpServletRequest and HttpServletResponse respectively and then the public service () method invokes a call to protected service () method.

 

c)    The protected service() method acts as a delegation method to delegate requests to doXXX() methods depending upon the type of HTTP request.

 

è  doXXX() methods:

 

The following protected methods are implemented by HttpServlet class in order to serve different types of client requests:

 

*       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

 

 

*       protected void doPost(HttpServletRequest request, HttpServletResponse   

response)  throws ServletException,IOException

 

*       protected void doHead(HttpServletRequest request, HttpServletResponse

response) throws ServletException,IOException

 

*       protected void doDelete(HttpServletRequest request, HttpServletResponse

response) throws ServletException,IOException

 

 

*       protected void doOptions(HttpServletRequest request, HttpServletResponse

                                                response) throws ServletException,IOException

 

*       protected void doPut(HttpServletRequest request, HttpServletResponse   

                                     response) throws ServletException, IOException

 

*       protected void doTrace(HttpServletRequest request, HttpServletResponse

response)throws ServletException,IOException

 

 

 

4.     ServletRequest interface:

 

 When the service () method of GenericServlet or the HttpServlet is called, an 

  instance of this object is created by the container.

 

  public interface ServletRequest.

 

  Some of the methods provided by this interface are discussed as below. These

  methods are used to access request parameters from the clients and to         

        manage the request attributes:

 

*       public String getParameter(String name): returns value of the parameter

      corresponding to the key ‘name’. It returns the first value of the list if  

      multiple entries are found corresponding to the same key. And a null value is

      returned if such parameter is not found.

 

*       public String[] getParameterValues(String name) : returns complete list of

      values i.e. returns a String array corresponding to the key ‘name’.

 

*       public Enumeration getParameterNames(): returns name of all parameters in

      the form of Enumeration. An empty enumeration is returned if no request

      parameters are associated with the request being processed.

 

*       public Map getParameterMap() : returns a Map object containing name of

      parameters as keys and set of their corresponding value being the values.

 

*       public Object getAtribute (String name): returns the value of the attribute named as ‘name’. A null is returned if no such attribute exists.

 

*       public Enumeration getAttributeNames(): returns Enumeration object      

      containing names of all attributes.

 

*       public void setAttribute(String name, Object attribute): sets value of attribute

      for a named attribute.

 

*       public void removeAttribute(String name): The named attribute is removed

      from the request. The setting and removal of attributes is useful to maintain

      sessions.

 

5.     ServletResponse interface:

 

  When the service () method of GenericServlet or the HttpServlet is called, an 

  instance of this object is created by the container.

 

   public interface ServletResponse

               

        Some of the important methods provided by this interface are discussed as   

          below:

 

*       public void setContentType(String type) : This method is used to set the

            MIME type for the response. A PrintWriter object is requested to write body 

            data to the response. Before such a request can be made, all response

            headers must be set.

 

*       public java.io.PrintWriter getWriter() throws java.io.Exception: For the same

            HttpServletResponse object, this method should be called only once. This   

            method is used to send character text in response.

 

*       public void resetBuffer(): This is used to reset the underlying buffer i.e. it

            cleans up the underlying buffer by deleting the contents .The status code or

            the response header remains unaffected after invocation of this method.

 

6.        HttpServletRequest  interface :

 

          This interface implements the ServletRequest interface. Hence, all the

          methods of ServletRequest are well available here. It is specific to HTTP

          requests.

 

          Mainly used methods in this interface are the methods which are used to

          access request parameters.

 

    Some other commonly used methods are:

   

 

a)    public String getQueryString() :

b)    public String getHeader(String name)

c)    public String getMethod() : returns type of HTTP request

 

7.        HttpServletResponse interface:

 

         This interface implements the ServletResponse interface. Hence, all the  

         methods of ServletResponse are well available here. It is specific to HTTP

         response.

    

   Some of the methods :

 

a)    public void sendError (int status): This method is used to output various status codes supported by HTTP.

 

b)    public String encodeURL(String url)

 

                             

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

A Simple Servlet

 

/* To import some packages which contain classes which are used by   

     servlet */

 

import javax.servlet.*;

import javax.servlet.http.*;

 

 

/* The servlet ‘SimpleServlet’ extends javax.servlet.http.HttpServlet which              

     is the base class for HTTP servlets */

 

public class SimpleServlet extends HttpServlet

{

 

     /* Overriding doGet() method of HTTPservletRequest */

 

         protected void doGet (HttpServletRequest request, HttpServletResponse

                                        response) throws ServletException, IOException

 

         {

                              /* Setting the content type for output using method of

                                   HttpServletResponse object */

 

                                     response.setContentType(“text/html”);

 

                             /* A PrintWriter object is being requested to write a

                                  response */

 

                                     PrintWriter out= response.getWriter();

 

                             /* Using the PrintWriter object which was obtained in  

                                   Previous step to write response of type text/html */

 

                                     out.println(“<HTML><HEAD><TITLE> A Simple “+

                                                   “Servlet</TITLE></HEAD></BODY></HTML>”);

 

                            /* Closing the PrintWriter object after the response has         

                                 been written */

 

                                     out.close();

         }

}

 

 

 

 

 

 

 

 

 

 

Single Thread Model in Servlets

 

For each servlet name there exists one servlet instance. For all other incoming requests, new threads are spawned from the same instance. That is, service () method might be invoked concurrently by many threads. What if this concurrent execution of service () method is to be avoided?

 

Java Servlet API defines a marker interface named as javax.servlet.SingleThreadModel to provide alternative if the service () method is thread unsafe. This interface is just a marker interface i.e. it does not provide definition of any method but its function is to let the container know that only one thread should be able to execute the service() method at any time.

 

It is suggested to avoid SingleThreadModel .This interface SingleThreadModel is deprecated in servlet API 2.4.

 

There are two approaches that a container may follow in order to ensure that no two threads can concurrently access the service () method. Also combination of both approaches can also be used:

 

v  Request Serialization:

 

              A single instance of the servlet is used for all client requests. Instead of sending multiple requests to that instance at the same time, the requests are sent to the instance in a serialized manner. While one client is being served, all the other

requests will keep waiting for availability of instance.

 

 

v  Instance Pooling:

 

              A pool of servlet instances is maintained by the container. The container picks up an instance from the pool for each new incoming request. The instance is  

returned to the pool after the request has been served.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Distinguishing among different users via concept of session:

 

A session is basically a unique connection between a server and a client to identify that multiple requests are sent by same client i.e. a session enables the server to identify a client across multiple requests.

 

Example:

 

After being login to an email account, the client needs to be identified by the server i.e. The server needs to verify that all the tasks like writing new mail, sending new mail are being done by the same authenticated client.However, the client may be asked to authenticate himself again and again but it is not a practical approach for large business transactions.

 

Other example is of banking transactions.

 

In case of large business transactions, flexibility can be maintained using facilities like:

 

Session:

 

It is required by the server to distinguish among different users. This can be achieved by putting specific request in a specific working session

 

State:

 

State refers to the information associated with the requests. Sometimes the information related to the previous requests is also required to handle a new incoming request.

 

The protocols which maintain the state are known as stateless protocols while stateless is the term used for protocols in which server do not remember any information about previous requests and treat each new request, even from the same client ,as a fresh request. HTTP is a stateless protocol.

 

 

 Maintaining the servlet sessions using Java Servlet API:

 

Java Servlet API provides an interface HttpSession which is used to represent session objects. And HttpServletRequest interface provides methods to create and track session:

 

a)    public HttpSession getSession( boolean create):

 

This method returns the HttpSession object which is associated with the request object representing the request being currently processed. The boolean argument tells the container whether new session is to be created if session does not exist already. If value of ‘create’ is true then a new session is created in case a session does not exist already. However, a null is returned if a session does not exist and  value of ‘create’ is false.

 

 

b)    public HttpSession getSession() :

 

It is similar to the above method with the only difference that it always create a session if one does not exist already.

 

A session consumes memory and other resources. So a session should be closed when not required. For ex: if a user closes his mail application without being logging out, the session is still using resources i.e. session is in inactive state. So it should be closed.

 

The methods provided by HttpSession interface can be grouped as:

 

è  Methods which deal with session lifetime

 

a)    public long getCreationTime() :

 

       This method returns the time of creation of session since January 1, 1970  

        00:00:00 GMT

 

b)    public int getMaxInactiveInterval():

 

        This method returns the time duration in seconds for which session will

        remain active between requests before expiring.

 

c)    public int setMaxInactiveInterval(int interval):

 

It is used to set the time duration in seconds for which session will remain active between requests before expiring .The session is automatically terminated after the specified time interval.

 

d)    public Boolean isNew() :

 

      It returns true or false indicating whether the session is new or not.

 

e)    public void invalidate() :

 

       This method is used to terminate a session. When a user logs out, this

       method is invoked to terminate his session.

 

 

 

è  Methods which associate state with sessions

 

 

a) public Object getAttribute(String name)

b) public Enumeration getAttributeNames(String name)

c) public setAttribute(String name, Object value)

d) public void removeAttribute(String name)

 

 (These methods have been discussed under ServletRequest interface)

 

 

 

 

References :

 

 

 http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html

 

 

       http://www.ecerami.com/applied_spring_2004/lectures/life_cycle.ppt

 

 

       http://java.sun.com/j2ee/tutorial/1_3-fcs/index.html

 

 

        http://www.stardeveloper.com/articles/display.html?article=2001062001&page=1