Posts Tagged ‘Technical’

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

Unix-FAQs

Wednesday, March 25th, 2009

 

 

Table of Contents:

 

1 FAQ.

1.1 Whenever I FTP a file, it puts in ^M at the end of each line. How do I remove them? 3

1.2 Can I map a key to include the Enter and/or Esc key? For example, ” ABC Services, Inc.[Enter][Enter]California, USA[Esc] 3

1.3 My group has a very long name, can I have vi type it out for me? 3

1.4 Escaping to the Shell with the:! Command. 3

1.5 Incorporating Shell Output Via the: r ! Command. 3

1.6 Can I import the output of a command line into vi? 3

1.7 VI Copy File to File. 4

2 Commonly used commands. 4

2.1 I’ve executed the following command “:10,15 s/this/that/g” in vi. Now I want to repeat the command for lines 20 through 25. how do I ring the command back up on the editor line? 4

2.2 How do I search for a word with blank spaces around it? 4

2.3 How do I create a temp file while in vi without knowing the filename of the file I’m editing? 4

2.4 Do you know of a vi command to change all text (upper and lower) on a line to uppercase? I used the ~ command, but it just reverses the case. 4

2.5 How do I change the contents of my entire file form a list of filenames to “mv filename /tmp/filename” ? 5

2.6 How do I execute the contents of my file without exiting or saving my vi session? 5

2.7 I have a file that contains 8000 user IDs that need to be disabled by putting “*DISABLED*” in the second field of /etc/passwd? 5

2.8 I have a file that contains over 5000 blank lines made out of 1 or more spaces (mostly 100 spaces). How do I remove them? 5

 

 

1 FAQ

 

1.1  Whenever I FTP a file, it puts in ^M at the end of each line. How do I remove them?

 

Ø  If you have tried: 1,$ s/^M//g you know that it doesn’t work. The ^M character is a single character which is created when transferring an ASCII file in BINARY mode. This usually happen when transferring from NT to UNIX. What you need to know here is that the ^M character is the Enter key.

 

Ø  VI allows you to duplicate the Enter key, or any other non-alphabet key (e.g. Esc, Backspace, Delete, etc.). Test it out by opening a line in vi and typing the following:

                   Control-V followed by Enter
                   Control-V followed by Backspace
                   Control-V followed by Delete

 

Ø  Now that you know how to generate a control key let’s remove all those pesky ^M’s:

                   :1,$ s/Control-V followed by Enter//g

                   You should see the following:

                   :1,$ s/^M//g

                   Does your file look cleaner now?

 

1.2 Can I map a key to include the Enter and/or Esc key? For example, ” ABC Services, Inc.[Enter][Enter]California, USA[Esc]

 

Ø  Let’s use your knowledge of the :map command and the ctrl-v combination to create the above map:

          :map # O ABC Services, Inc.Control-V followed by Enter Control-V followed by           EnterCalifornia, USAControl-V followed by Esc

          Type the above in one line.

          You should see the following:

          :map # O ABC Services, Inc.^M^MCalifornia, USA^[

 

Ø  Test your map out by moving your cursor to the middle of your file and pressing the # key (shift-3). You should see either:

          ABC Services, Inc.

          California, USA

          or

          ABC Services, Inc.

          California, USA

          Depending on whether your autoindent is set (remember: set ai?).
          The: abbreviate command makes life easier for you when you are in the insert/append mode. The: abbreviate command can be   

          abbreviated to:

          :ab

 

1.3 My group has a very long name; can I have VI type it out for me?

 

Ø  If your group name is UNIX Software System Support, you can have vi abbreviate it to sss. All you have to do is:

          : abbreviate sss UNIX Software System Support

          or

          : ab sss UNIX Software System Support

 

Ø  Now test your abbreviation out by opening up a line and start typing the following:

          I have been with the sss Team for # months.

 

Ø  You should see sss change to UNIX Software System Support as soon as you hit the spacebar after sss.

 

Ø  What do you think would happen if you are writing a children's book and you type the following?

          This is a snake. A snake goes hisss.

          Try it out.

 

1.4 Escaping to the Shell with the:! Command

 

Ø  You can escape to the shell and run commands without exiting your vi session. Many times you do this because you are not ready to do a: wq yet. Or you are afraid that opening another xterm to look at your lpstat command will crash your laptop.

 

Ø  For example, you want to check if your print job has completed yet, you can run the following command while in vi:

          :!lpstat

          The ! takes you into a child shell to execute your command. and prompts you to [Hit return to continue] when you’re done.

 

1.5 Incorporating Shell Output Via the: r ! Command

 

Ø  Many times when you are documenting, you want to insert the contents of a file, or standard output into your document. This command does exactly that.

 

1.6 Can I import the output of a command line into VI?

 

Ø  You are documenting a script and would like to import some output into your documenting. Your goal is to show the permissions for the file, and the contents of the file. One way it to cut and paste with 2 windows open.

 

Ø  The vi way would be to move your cursor to where you want the output to appear in your file and type:

          :r !ll ring10

          You see the following in your file:

          -rwxr-xr-x 1 sss3 sss 54 Jan 27 11:10 ring10

 

Ø  Then move the cursor to where you want the content of your file and type:

          :r ring10

          You see the following in your file:

          for i in 0 1 2 3 4 5 6 7 8 9
          do
          echo ^G
          sleep 1
          done

 

1.7 VI Copy File to File

 

Here is how to copy the required number of lines from one file to another in VI editor.  First use the following key combinations in the source file.

 

Ø  Press ESCAPE

Ø  Press Shift “(Shift double quotes)

Ø  Press a

Ø  Press the number of lines you want to copy

Ø  press y followed by another y

Ø  Now press ” : ” (COLON) to get the vi prompt.

Ø  Hit e “Destination file name”

Ø  Once you enter the Destination file go to the line where you want the lines copied to be inserted.

Ø  Press ESCAPE.

Ø  Press SHIFT “(Double quotes).

Ø  Press a.

Ø  Press p.

Ø  The lines get copied.

 

2 Commonly used commands

 

2.1 I’ve executed the following command “:10,15 s/this/that/g” in vi. Now I want to repeat the command for lines 20 through 25. how do I ring the command back up on the editor line?

 

                   The key here is to plan ahead. This is one way I would approach it:

                   Create an abbreviation first:

                        :ab str s/this/that/g

                   Then you can execute your replacement as often as you want on any line(s) by typing:

                        :10,15 str space
                   :20,25 str space
                   :40,$-2 str space

                   Note that the str MUST be followed by a space for the :ab to take effect.

 

2.2 How do I search for a word with blank spaces around it?

 

                   Type the following:

                        /\[space]string\[space][enter]

                   Don’t type each character in the square brackets (or the square bracket).

 

2.3 How do I create a temp file while in vi without knowing the filename of the file I’m editing? 

 

                         One way is to use :w %.tmp
                   This says write (save) contents to the filename.tmp. % is a placeholder for the name of the file.

 

2.4 Do you know of a vi command to change all text (upper and lower) on a line to uppercase? I used the ~ command, but it just reverses the case.

 

                        Type the following

                        :s/[a-z]/\u&/g

                   The \u changes case to upper (\l to lower)
                   The & is the placeholder for each pattern/character found.

 

2.5 How do I change the contents of my entire file form a list of filenames to “mv filename /tmp/filename” ?

 

                   Content of vi’ed file:

                   filea
                   fileb
                   :
                   filex
                   lastfile

                        Type the following:

                        :1,$ s#.*#mv & /tmp/&#

                   The & is the placeholder for each pattern/character found.

 

2.6 How do I execute the contents of my file without exiting or saving my vi session?

 

                        Type the following:

                        :w !sh

                   This essentially means to write the entire editing buffer to a shell for execution. At this point you can quit vi, and the job is

                   done.

 

2.7 I have a file that contains 8000 user IDs that need to be disabled by putting “*DISABLED*” in the second field of /etc/passwd?

 

                   Content of vi’ed file:

                   c04821
                   c04822
                   c05035
                   :
                   :
                   c05555
                   c15556

                   Type the following on the same line (no carraige returns):

                        :1,$ s#.*#grep -v ^&: pwd > /etc/passwd; awk -F: ‘/^&:/ {print                                                  $1″:NONE:”$3″:”$4″:”$5″:”$6″:”$7}’ pwd >> /etc/passwd;

                        cat /etc/passwd >            

                        pwd#

 

2.8 I have a file that contains over 5000 blank lines made out of 1 or more spaces (mostly 100 spaces). How do I remove them?

 

                        : Type the following (don’t forget the space before the asterix/star character):

                        g/^ *$/d

 

 

 

Servlets FAQ

Tuesday, March 10th, 2009

TABLE OF CONTENTS

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

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

How can I further optimize my servlets?

How do I set my CLASSPATH for servlets?

Why doesn’t my servlet work inside a <SERVLET> tag?

How do I fully shut down the server? My browser says “the server returned an invalid or unrecognized response” — what gives?

What is the HelloWorld Servlet?

How do I get the name of the currently executing script?

How do I mix JSP and SSI #include?

How do I ensure that my servlet is thread-safe?

How do I use Session Tracking?

How can I detect whether the user accepted my cookie?

How do I integrate HTML design into my Servlet? How do I send email from a servlet?

Are there any ISPs that will host my servlets?

What is the difference between URL encoding and URL rewriting?

How can my applet communicate with my servlet?

How can I debug my servlet? How do I create an image (GIF, JPEG, etc.) on the fly from a servlet?

How do I upload a file to my servlet?

How do I access a database from my servlet?

 

 

 

 

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”!

 

Can a servlet maintain a JTA UserTransaction object across multiple servlet invocations?
 

No. A JTA transaction must start and finish within a single invocation (of the service() method). Note that this question does not address servlets that maintain and manipulate JDBC connections, including a connection’s transaction handling.

 

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 further optimize my servlets?
 

You can always wring out some efficiency by making use of a StringBuffer or ByteArray.

For example, instead of sending your HTML to the client using a PrintWriter or some other output stream, you can write it out to a StringBuffer, and send it to the client using just one write invocation. Of course, you’ll have to indicate the length of your data stream in the HTTP header too as shown below:

 PrintWriter out = res.getWriter();

 StringBuffer sb = new StringBuffer();

 …

 //concatenate html to StringBuffer

 //set len and write it out

 res.setContentLength(sb.length());

 out.print(sb);

 

How do I set my CLASSPATH for servlets?
 

That depends.

For developing servlets, just make sure that jsdk.jar (in the lib subdirectory of the JSDK (http://java.sun.com/products/servlet/) ) is in your CLASSPATH, and use your normal development tools (javac and so forth).

For running servlets, you need to set the CLASSPATH for your servlet engine. This varies from engine to engine. Each has different rules for how to set the CLASSPATH, which libraries and directories should be included, and which libraries and directories should be excluded. Note: for engines that do dynamic loading of servlets (e.g. JRun, Apache Jserv), the directory containing your servlet class files shoud not be in your CLASSPATH, but should be set in a config file. Otherwise, the servlets may run, but they won’t get dynamically reloaded.

The Complete CLASSPATH Guide for Servlets (http://www.meangene.com/java/classpath.html) by Gene McKenna (mckenna@meangene.com) has detailed instructions on how to set your CLASSPATH for JavaWebServer and JRun.

 

Is it the “servlets” directory or the “servlet” directory?
 

For Java Web Server:

  • on the file system, it’s “servlets”
    c:\JavaWebServer1.1\servlets\DateServlet.class
  • in a URL path, it’s “servlet”
    http://www.stinky.com/servlet/DateServlet

Other servlet engines have their own conventions. Usually on the file system it’s “servlets” and in a URL it’s “/servlet” (which is an alias or virtual path). ]

 

Why doesn’t my servlet work inside a <SERVLET> tag?
 

If you use your servlet inside an SSI, you must use res.getOutputStream() and not res.getWriter(). Check the server error logs for more details.

 

How do I support both GET and POST protocol from the same Servlet?
 

The easy way is, just support POST, then have your doGet method call your doPost method:

 

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException

{

    doPost(req, res);  

}

Note that implementing the service() method is usually not what you want to do, since HttpServlet provides its own implementation of service() that turns around and calls doGet(), doPost(), etc.

Lee Crocker (LCrocker@INFORMANT.COM): “It’s probably cleaner not to override service() when extending HttpServlet. The existing service method just calls doGet(), doPost(), etc. as appropriate, so you can certainly override it if you feel like it, but then you wind up not only treating GET and POST identically, but also all other HTTP commands, like HEAD, TRACE, and OPTIONS. If you want GET and POST to do the same thing, just have doGet() and doPost() call the same private method that does all the work.”

 

How do I fully shut down the server?
 

For JWS, under Windows, pressing control-C doesn’t fully shut down the server. You should use the Admin Tool and click “Shut Down”. (Or you can hit ctl-alt-del, find “JREW” in the list, and “End Task”.)

 

My browser says “the server returned an invalid or unrecognized response” — what gives?

 

This is probably due to a NullPointerException being thrown. There’s a bug in JWS 1.1 whereby it doesn’t correctly log these exceptions.

The solution is to put your doPost() method inside a try block and catch NullPointerException. See the debugging question in this FAQ for more details and source code.

 

What is the HelloWorld Servlet?

 

public class HelloHttpServlet extends HttpServlet

{

    public void doGet(HttpServletRequest req, HttpServletResponse res)

    throws IOException, ServletException

    {

          String name = req.getParameter(”name”);

          if (name == null) name = “Joe”;

          res.setContentType(”text/plain”);

          ServletOutputStream out = res.getOutputStream();

          out.println(”Hello, ” + name + “!”);

    }

}

This code responds to an invocation of the form

 

http://myserver.foo.com/servlet/HelloHttpServlet?name=Fred

 

How do I get the name of the currently executing script?
 

Use req.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info. For example:

URL http://www.purpletech.com/servlets/HelloEcho/extra/info?height=100&width=200
getRequestURI /servlets/HelloEcho/extra/info
getServletPath /servlets/HelloEcho
getPathInfo /extra/info
getQueryString height=100&width=200

This is useful if your form is self-referential; that is, it generates a form which calls itself again. For example:

 

out.println(”<FORM METHOD=POST ACTION=\”" +

        res.encodeURL(req.getServletPath()) +

        “\”>”);

out.println(”<INPUT NAME=value>”);

out.println(”<INPUT TYPE=submit>”);

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

(encodeURL adds session information if necessary. See the Sun Servlet Tutorial and this FAQ’s Session Tracking question. Note that this method was renamed from “encodeUrl” to the properly-capitalized “encodeURL” somewhere around version 2.1 of the servlet spec.)

Note that early versions of Java Web Server and some servlet engines had a bug whereby getRequestURI would also return the GET parameters following the extra path info.

 

How do I mix JSP and SSI #include?

 

If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.

 

<!–#include file=”data.inc”–>

But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says: If your data.inc file contains jsp code you will have to use

 

<%@ vinclude=”data.inc” %>

The <!–#include file=”data.inc”–> is used for including non-JSP files.

 

How do I ensure that my servlet is thread-safe?

 

This is actually a very complex issue. A few guidelines:

  • 1. The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don’t have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.
  • 2. Every new client request generates a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth).
  • 3. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other’s toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword.
  • 4. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn’t synchronize the service() method! (Or doPost(), doGet() et al.)
  • 5. A simple solution to synchronizing is to always synchronize on the servlet instance itself using “synchronized (this) { … }”. However, this can lead to performance bottlenecks; you’re usually better off synchronizing on the data objects themselves.
  • 6. If you absolutely can’t deal with synchronizing, you can declare that your servlet “implements SingleThreadModel”. This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: “If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.” Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it’s more difficult to share data across instances than within a single instance.
  • 7. To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use Session Tracking.
  • 8. The destroy() method is not necessarily as clean as the init() method. The server calls destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun’s Servlet Tutorial has an example of how to do this with reference counting.
  • 9. destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the “closing a JDBC connection” example in Sun’s Tutorial.

 

How do I use Session Tracking?

 

See section 2.3 of the Servlet Essentials tutorial (http://www.novocode.com/doc/servlet-essentials/) . Also see The Session Tracking API (http://webreview.com/wr/pub/1999/01/08/bookshelf/index.html) , excerpted from Java Servlet Programming (http://www.oreilly.com/catalog/jservlet/) by Jason Hunter (http://webreview.com/wr/pub/au/Hunter_Jason).

A point I haven’t seen emphasized enough is that you should only add objects that are serializable to an HttpSession. Specifically, a JDBC Connection object is not serializable, so should not be added to the session (despite the example in Jason Hunter’s otherwise admirable Java Servlet Programming). If you’d like to associate a connection with a session, then store some arbitrary, unique handle in the session, then use that to key off your own hashtable of connections. (Make sure upon retrieval that the returned connection is not null, and if it is, create a new connection!)

The reason is that sessions may, at the whim of the server, be swapped out to disk, in order to save memory or reboot the server. This behavior can be disabled by setting a configuration parameter in your server or servlet engine. (I can’t remember offhand what these are — please email me if you know.) From the spec: Some servlet engine implementations will persist session data or distribute it amongst multiple network nodes. For an object bound into the session to be distributed or persisted to disk, it must implement the Serializable interface.

 

How can I detect whether the user accepted my cookie?

 

Here’s a clever trick: use a redirect. Drop a cookie on the HttpServletResponse object, then call resp.sendRedirect() to a “phase two” servlet. The “phase two” servlet then tests whether the cookie was sent back to it. If so, that means the user accepted the cookie the first time; if not, it means that either the client rejected the cookie, or the browser doesn’t support cookies.

Note that this technique only works if the “phase two” servlet is hidden from the user; if the user can jump directly to the test phase, then the servlet can’t tell the difference between newly-arrived clients and cookie-unfriendly clients. That means you should send a redirect from the test phase, to make sure the user doesn’t have a chance to bookmark the test phase’s URL.

Alex Chaffee (http://www.stinky.com/alex/, alex@jguru.com) has written a Servlet that demonstrates this technique called CookieDetector (http://www.purpletech.com/code/CookieDetector.html)

 

How do I integrate HTML design into my Servlet?

 

The question can be rephrased, “How can I design a work flow that incorporates HTML designers and programmers to build a dynamically generated web site that will keep expanding and growing over time?” This is a special case of the intractable Content Management Problem of the Web in general. The real problem is to allow HTML designers (that is, humans) to use their favorite HTML editing tools without learning Java, and to allow marketing people (arguably humans) to change the look of the site on a whim, without having to alter the database access code inside the servlet. (And vice versa — to alter the business logic and data access without altering the user interface.)

See my article at Servlet Central (http://www.servletcentral.com/1998-12/designprocess.dchtml) for an expansion on these themes.

There are many, many possibilities… The list below is not complete, but should give you some guidelines.

A. Hardcode HTML. You can just put HTML inside of print statements in your Servlet’s doGet() or doPost() method.
Pro: easy to code, easy to understand for the programmer.
Con: difficult to understand for the designer; when a change has to be made, the programmer has to wait for the designer to finish her HTML, then re-hard-code it all back into print statements, then make sure the generated HTML actually does what the original HTML did. Basically, good for a hello world servlet, not good for a real web site.

B. Server Side Includes (SSI). Use the <SERVLET> tag inside your HTML file (and rename it .shtml). The HTML designers will make pretty pages; your servlets will output small pieces of text that get spliced in to the web page by the server.
Pro: separates UI (HTML) and code.
Con: You have two possible end paths with SSI: either your servlet outputs many tiny bits of text with no HTML tags, or your servlet outputs a big bunch of text with embedded HTML tags. In the first case, your code can’t take advantage of its knowledge of the structure of the data — for example, you can’t format an HTML table from a database. In the second case, you’re back to hardcoding HTML, thus making it hard to change the look of your pages.

C. Presentation Templates. This is a good way to put common navigation elements (button bar, credits, etc) on all of your pages. The technology is built in to the Java Web Server, and implemented by several (though not all) of the servlet engines.
Pro: you don’t have to enter in the same common HTML for all the countless pages in your web site.
Con: your servlet code still has to hardcode HTML if it wants to be powerful (see item B, SSI).

D. JSP Java Server Pages. You write files in HTML format, and embed actual Java code inside the HTML. This is kind of like using JavaScript, only it’s on the server, and it’s real Java. This is directly parallel to Microsoft’s ASP.
Pro: it’s really cool; you only need a single file to do both UI and layout code; you don’t have to type “println” so much.
Con: if you do anything interesting, then your HTML designers will get really confused looking at the interlaced Java and HTML code — so make sure to put the complicated code inside a JavaBean where it belongs, not in the JSP page.

The new version of the JSP spec has lots of features for integrating with JavaBeans, which is a great way to separate user interface (JSP) from data and business logic (beans). See also the JSP FAQ (see our References section for a link).

Halcyon Software has a product called Instant ASP, which allows you to execute Microsft IIS-style ASPs (including code in VBScript, Jscript, Perl, Java, and JavaScript) in any Servlet Engine. Also Live Software has CF_Anywhere, which executes Cold Fusion CFML pages. See the References section for links.

E. Write your own page parser. If for some reason you’re not happy with the standard mechanisms for doing templates (see B-D above), you can always write your own parser. Seriously. It’s not rocket science.

F. HTML Object Model Class Libraries e.g. htmlKona, XML. With these class libraries, you write code and build an object model, then let the objects export HTML. This doesn’t really work for complicated layouts — and forget about letting your designer use an HTML editor — but it can be useful when you have a highly dynamic site generating HTML, and you want to automate the process. Unfortunately, you still have to learn HTML, if only to understand and validate the output. See the References section of this FAQ for a listing of some class libraries that can help.

G. Do it all yourself Develop a database-driven content management system. Think C|Net. It has a lot of standard content, but the database is king. HTML designers have little pieces of the page that they can play with, but ultimately they’re just putting content into a database, and the site (servlet) is generating every page request dynamically. This sort of system is very difficult to design and build, but once you’ve built it, it can really pay off — but only if you have dozens of writers, editors, designers, and programmers all working on the same site on an ongoing basis.

For a brief list of alternate page template systems, see the References section of this FAQ.

 

How do I send email from a servlet?

 

From: James Cooper (pixel@bitmechanic.com) GSP and GnuJSP both come with SMTP classes that make sending email very simple. if you are writing your own servlet you could grab one of the many SMTP implementations from www.gamelan.com (search for SMTP and java). All the ones I’ve seen are pretty much the same — open a socket on port 25 and drop the mail off. so you have to have a mail server running that will accept mail from the machine JServ is running on.

See also the references section for a good list of Java email resources, including SMTP and POP classes.

 

Are there any ISPs that will host my servlets?

 

The Adrenaline Group maintains a list of ISP’s who host Java Servlets (http://www.adrenalinegroup.com/jwsisp.html) . Of these, a few have also said that they can host Java applications:

Daniel Kehoe (kehoe@fortuity.com) has had “very happy experiences” with Silicon Valley Web Hosting (http://www.svwh.net/) for several clients.

(http://www.servlets.net) is an ISP geared towards hosting servlets.

Please report any experiences, good or bad, you have with these services to &feedback;.

]

 

What is the difference between URL encoding and URL rewriting?

URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network — basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).

Example: changing “We’re #1!” into “We%27re+%231%21″

URL Rewriting is a technique for saving state information on the user’s browser between page hits. It’s sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.

Example: changing <A HREF=”nextpage.html”> into
<A HREF=”nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE”> (or whatever the actual syntax is; I forget offhand)

There’s also a feature of the Apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache FAQ (http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config) .

 

How can my applet communicate with my servlet?

 

It’s pretty straightforward. You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn’t know the difference. (Of course, you can write a servlet that is only called from your applet, in which case it *does* know the difference…)

For more detail, you can see the Sun Web Server FAQ (http://www.sun.com/software/jwebserver/faq/faq.html) Questions C8 (http://www.sun.com/software/jwebserver/faq/faq.html#c8) and C9 (http://www.sun.com/software/jwebserver/faq/faq.html#c9) . Also, Chad Darby has an article with source code (http://www.j-nine.com/pubs/applet2servlet/index.htm) on the subject. And Netscape DevEdge Online has a similar article – Applet-to-Servlet Communication for Enterprise Applications (http://developer.netscape.com/viewsource/index_frame.html?content=fields_servlet/fields_servlet.html) skip to the “Communication Tactics” section to get to the good part.

 

How can I debug my servlet?

 

Hoo boy, that’s a tough one.

First off, you should always do your own exception handling. An uncaught exception can silently kill your servlet, and if you don’t know where to look in the log files, or if your server has a bug in it whereby it silently swallows certain exceptions, you’ll have no idea where the trouble is.

The following code sets up a catch block that will trap any exception, and print its value to standard error output and to the ServletOutputStream so that the exception shows up on the browser (rather than being swallowed by the log file). Chances are that any error is in your code; the exception shows you what line the problem happened at. (If you see “Compiled Code” instead of line numbers in the exception stack trace, then turn off the JIT in your server.)

 

res.setContentType(”text/html”);

ServletOutputStream out = res.getOutputStream();

try {

  // do your thing here

  …

}

catch (Exception e) {

  StringWriter sw = new StringWriter();

  PrintWriter pw = new PrintWriter(sw);

  e.printStackTrace(pw);    

  out.println(”<pre>”);

  out.print(sw.toString());

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

}

Lately, I’ve started catching all Throwables, just in case. I know this is bad form but what are you gonna do?

Next, you should make liberal use of the log() method, and you should keep your own log files. Again, don’t trust the server to do the right thing. Also, printing the log after every request can help debugging because you can immediately see the output of your servlet without going into the server-side log files. (Another problem this avoids is that some servlet engines forget to flush their logs after each request, so even if you go to the server, you won’t see the most recent log messages.)

Here’s some source code you can add to any HttpServlet that keeps an in-memory log:

 

StringBuffer logBuffer = new StringBuffer();

 

public void log(String s) {

        s = new Date().toString() + “: ” + s;

        System.err.println(s);

        logBuffer.append(s);

        logBuffer.append(”\n”);

        super.log(s);

}

And here’s some code that you can add to the end of your doGet or doPost method that prints out the entire log after each request:

 

out.println(”<HR>\n<H3>Error log this session:</H3>\n<PRE>”);

out.println(logBuffer.toString());

out.println(”</PRE><P>”);

Both of these should be disabled once you actually ship your servlet, but they can be very useful during development and debugging.

You should remember to use servletrunner (renamed “JSDK WebServer” with the JSDK version 2 — run with the script startserver) to debug your servlet. It’s a tool that ships with the JSDK that basically starts up a miniature web server that runs your servlet inside itself. It means you don’t have to stop and restart your real web server every time you recompile your servlet. It also affords a more pure environment, so you can make sure your servlet truly conforms to the spec before you try to run it inside a (possibly buggy or nonstandard) servlet engine.

A few IDEs support servlet debugging. Symantec Cafe claims to have a fairly robust system for doing visual source-level debugging of servlets (as well as RMI, CORBA, and EJB objects). [If anyone has any experience with Cafe or other IDEs, please email &feedback;.] May Wone (abc408@hotmail.com) writes:

I am debugging servlets running servletRunner inside of IBM’s VisualAge for Java.

On my first servlet project, I used a ton of log messages for debugging.

This is my second servlet project, and this debugging technique has enhanced my productivity many folds. I am able to set code break points, step through each line of code, inspect all the objects visible to this class as well as view the objects in the current stack. I can also view, suspend, resume threads.

The setup instructions are at: (http://www.ibm.com/java/education/server-side/server-side.html)

jRun also claims to have excellent log file support as well as some debugging facilities.

Eric Gilbertson (eric@bitsource.com) adds:

Another way to debug servlets is to invoke JWS with java_g and then attach to the process using any debugger that is capable of attaching to a running Java process given a debug password. To do this invoke JWS as follows:

 

java_g.exe -debug -Dserver.name=”javawebserver” [extra args...] com.sun.server.ServerProcess

jdb password=[password]

This will start the Web server process and echo a password. The password may be then used with jdb to attach to the process. Note that this will start only the Web server, not the admin server.

Sun does not advertise this mechanism which in my mind is the only way to debug non-trivial servlets.

 

How do I create an image (GIF, JPEG, etc.) on the fly from a servlet? 

 

To create an image or do image processing from Java, there are several packages and classes available. See the References section for a list.

Once you have an image file in your servlet, you have two choices:

  • 1. Write the file to disk and provide a link to it. Make sure you write it to a location that’s in your web server directory tree (not just anywhere on the server’s disk). (Note that in some servlet engine setups, the servlet directory is not accessible by the web server, only by the servlet engine, which means you won’t be able to access it through an http:// URL.) You can either send an IMG tag in the HTML your servlet is outputting, or send an HTTP redirect to make the browser download the image directly (as its own page). (CookieDetector (http://www.purpletech.com/code/CookieDetector.html) has an example, with source code, of sending a redirect.)
    Pro: the image can be cached by the browser, and successive requests don’t need to execute the servlet again, reducing server load.
    Con: the image files will never be deleted from your disk, so you’ll either have to write a script to periodically clean out the images directory, or go in and delete them by hand. (Or buy a bigger hard disk :-) ).
  • 2. Output the image directly from the servlet. You do this by setting the Content-type header to image/gif (for GIFs), or image/jpeg (for JPEGs). You then open the HttpResponse output stream as a raw stream, not as a PrintStream, and send the bytes directly down this stream using the write() method.

Focus on Java (http://java.miningco.com/library/weekly/aa090299.htm) has a brief article describing the use of the Java 2 JPEGCodec class.

 

How do I upload a file to my servlet? 

From Thomas Moore’s Servlet FAQ:

Form-based file upload requires a couple of steps.

The server must supply (and the client must support) encoding type multipart/form-data. Most current browsers do, but it’s not a guarantee. Secondly (and this is usually the trickiest part), your servlet has to parse the binary data and do something with it (e.g., write it to a file on the server).

The intrepid programmer is referred to RFC 1867 for cluefulness on how to parse this data. Less brave souls can use either Jason Hunter’s implementation of a MultipartRequest (available from http://www.servlets.com), or CParseRFC1867 (available from http://www.servletcentral.com).

Note that the source code is available for both of these examples, but both assume that you will be writing the file to a file on the server. Other uses (e.g. storing the file as a binary object in a database) will require adaptation.

There is a multipart/form parser availailable from Anders Kristensen (http://www-uk.hpl.hp.com/people/ak/java/, ak@hplb.hpl.hp.com) at http://www-uk.hpl.hp.com/people/ak/java/#utils. JavaMail also has MIME-parsing routines (see the References section).

Here is an example of HTML code that allows file upload, courtesy of Detlef Pleiss (dpleiss@os-net.de):

 

<FORM ENCTYPE=”multipart/form-data” method=post

action=”…”> put the servlet URL here, of course

<INPUT TYPE=”file” NAME=”mptest”><INPUT TYPE=”submit” VALUE=”upload”>

</FORM>

The input type “file” brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet uses the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse. Tested with IE4, IE5 and Netscape 4.5.

 

How do I access a database from my servlet?

Since JDK 1.1, Java comes with a package called JDBC (Java Database Connectivity). JDBC allows you to write SQL queries as Java Strings, pass them to the database, and get back results that you can parse. To learn how to write JDBC code, check the tutorials on Sun’s web site, and read the Javadoc API documentation for package java.sql. To install JDBC on your system, you need to locate a JDBC Driver for your particular database and put it in your classpath. Fortunately, most databases these days ship with a 100% Pure Java driver (also known as a “Type IV” driver), including Oracle, Sybase, Informix, etc. Check the documentation for your database engine for installation instructions.