Subscribe: E-Surfer's Weblog
Added By: Feedage Forager Feedage Grade B rated
Language: German
ajax  apache  code  file  form  java org  java  javascript  jsp  org apache  org  page  param param  param  text  web 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: E-Surfer's Weblog

E-Surfer's Weblog

E-Surfer's Weblog - Thinking, feeling in JAVA, J2EE, XML, Web Services development

Last Build Date: Tue, 12 Jul 2016 04:26:30 -0400

Copyright: Copyright 2016

IBM Open Source Application Server Gains Support of More Than 600 Partners in Six Months

Fri, 17 Nov 2006 20:02:00 -0500

IBM Open Source Application Server Gains Support of More Than 600 Partners in Six Months ? IBM has announced that more than 600 independent software vendors (ISVs) and systems integrators have joined IBM's WebSphere Application Server (WAS) Community Edition partner initiative since it was launched just six months ago. WAS Community Edition is IBM's open source application server based on Apache Geronimo.

SYS-CON Announces Two New "AJAXWorld University Bootcamp" Dates

Sat, 11 Nov 2006 18:34:00 -0500

SYS-CON Announces Two New "AJAXWorld University Bootcamp" Dates ? SYS-CON Events has announced that, due to popular demand, more 'AJAXWorld University Bootcamps' ( will be taking place on two new dates in 2007. The next two dates are January 22, 2007 and March 19, 2007 - both in New York City, at the historic Roosevelt Hotel in midtown Manhattan.

Web 2.0 vs Web 1.0: Why Ajax is Conceptually Better

Sat, 11 Nov 2006 18:21:00 -0500

Web 2.0 vs Web 1.0: Why Ajax is Conceptually Better ? We now serve 'pure data' or content, without all the formatting clutter that scrambled our data back in Web 1.0. The reduction of redundancy is a nice side effect, not having to download the layout on every refresh.

Canonical and Sun Expand Joint Ubuntu/Sun Presence in the Enterprise and Open Source Communities

Sat, 11 Nov 2006 18:18:00 -0500

Canonical and Sun Expand Joint Ubuntu/Sun Presence in the Enterprise and Open Source Communities ? Sun Microsystems, and Canonical, the commercial sponsor of the rapidly-growing Ubuntu GNU/Linux distribution, have announced that the open-source Java Enterprise Edition 5 application server (specifically, the GlassFish Community reference implementation) will be made available on the widely popular Ubuntu operating system.


Fri, 20 Oct 2006 11:30:00 -0400

DEC HEX CHR DEC HEX CHR DEC HEX CHR 0 00 NUL 43 2B + 86 56 V 1 01 SOH 44 2C , 87 57 W 2 02 STX 45 2D - 88 58 X 3 03 ETX 46 2E . 89 59 Y 4 04 EOT 47 2F / 90 5A Z 5 05 ENQ 48 30 0 91 5B [ 6 06 ACK 49 31 1 92 5C \ 7 07 BEL 50 32 2 93 5D ] 8 08 BS 51 33 3 94 5E ^ 9 09 TAB 52 34 4 95 5F _ 10 0A LF 53 35 5 96 60 ` 11 0B VT 54 36 6 97 61 a 12 0C FF 55 37 7 98 62 b 13 0D CR 56 38 8 99 63 c 14 0E SO 57 39 9 100 64 d 15 0F SI 58 3A ? 101 65 e 16 10 DLE 59 3B ? 102 66 f 17 11 DC1 60 3C < 103 67 g 18 12 DC2 61 3D = 104 68 h 19 13 DC3 62 3E > 105 69 i 20 14 DC4 63 3F ? 106 6A j 21 15 NAK 64 40 @ 107 6B k 22 16 SYN 65 41 A 108 6C l 23 17 ETB 66 42 B 109 6D m 24 18 CAN 67 43 C 110 6E n 25 19 EM 68 44 D 111 6F o 26 1A SUB 69 45 E 112 70 p 27 1B ESC 70 46 F 113 71 q 28 1C FS 71 47 G 114 72 r 29 1D GS 72 48 H 115 73 s 30 1E RS 73 49 I 116 74 t 31 1F US 74 4A J 117 75 u 32 20 (space) 75 4B K 118 76 v 33 21 ! 76 4C L 119 77 w 34 22 " 77 4D M 120 78 x 35 23 # 78 4E N 121 79 y 36 24 $ 79 4F O 122 7A z 37 25 % 80 50 P 123 7B { 38 26 & 81 51 Q 124 7C | 39 27 ' 82 52 R 125 7D } 40 28 ( 83 53 S 126 7E ~ 41 29 ) 84 54 T 127 7F DEL 42 2A * 85 55 U [...]

Create checked radio button dynamically

Thu, 21 Sep 2006 23:00:00 -0400

I meet some trouble when creating radio buttons through javascript. My code is something like this:

function createRadioButton(elt_name, elt_value, elt_label, is_selected) {
    var inputElement = document.createElement('input');
    inputElement.setAttribute('type', 'radio');
    inputElement.setAttribute('name', elt_name);
    inputElement.setAttribute("value", elt_value);
    var func = new Function("alert(this.value + ' is selected!')");
    inputElement.onclick = func;
    if (is_selected) {
        inputElement.setAttribute("checked", "checked");
    var divElement = document.getElementById("container");

This works perfectly in Firefox. but in Internet Explorer the radio buttons can't be selected. After googling the internet, I find a solution which works well in IE:

var inputElement = document.createElement('');

However, another problem arises. IE leaves the radio button unchecked even I set the checked status in my javascirpt like this:

inputElement.setAttribute("checked", "checked");

It seems that this has no side-effect on the behavior of IE before I insert the radio button into the DOM. So I move the code used to set the checked attribute down to after the statement used to insert the radio button into the document, it works fine.

The following is the full source code:

create radio button

Create radio button dynamically

Krugle - a search engine for source code and code-related information

Thu, 21 Sep 2006 03:12:00 -0400

Krugle makes it easy for developers to find source code and technical information by using its simple, friendly, ajax-enabled interface. It also lets developers add their own comments to entire code files or specific lines of code, allowing for useful code-centric communication between developers.

For more information about Krugle, please visit

In-Place editing with in JSP

Mon, 18 Sep 2006 04:40:00 -0400

Ajax makes it possible to refresh defined parts of the user interface without refreshing the whole web page. An responsive Ajax enabled web site can attract more customers and get more business. With the goodness of Ajax, I implement the in-place editing function in my recent e-commerce web application. Our customers can update the quantity of item(s) in the shopping cart without seeing the blank web page. The in-place editing function can be implemented by using the In Place Editor easily. For those new to, it is an add-on to the Prototype framework, which provides easy-to-use, cross-browser user interface JavaScript libraries to create rich interface web sites and web applications. The current version of is 1.6.4. It can be download at The constructor of Ajax.InPlaceEditor takes three parameters. The first is the element that should support in-place editing. The second is the url to submit the changed value to. The server should respond with the updated value (the server might have post-processed it or validation might have prevented it from changing). The third is a hash of options. new Ajax.InPlaceEditor( element, url, [options]); Supported options are (all are optional and have sensible defaults): Option since default Description okButton V1.6 ?true? If a submit button is shown in edit mode (true,false) okText V1.5 ?ok? The text of the submit button that submits the changed value to the server cancelLink V1.6 ?true? If a cancel link is shown in edit mode (true,false) cancelText V1.5 ?cancel? The text of the link that cancels editing savingText V1.5 ?Saving?? The text shown while the text is sent to the server clickToEditText V1.6 ?Click to edit? The text shown during mouseover the editable text formId V1.5 id of the element to edit plus ?InPlaceForm? The id given to the element externalControl V1.5 null ID of an element that acts as an external control used to enter edit mode. The external control will be hidden when entering edit mode and shown again when leaving edit mode. rows V1.5 1 The row height of the input field (anything greater than 1 uses a multiline textarea for input) onComplete V1.6 ?function(transport, element) {new Effect.Highlight(element, {startcolor: this.options.highlightcolor});}? Code run if update successful with server onFailure V1.6 ?function(transport) {alert(?Error communicating with the server: ? + transport.responseText.stripTags());}? Code run if update failed with server cols V1.5 none The number of columns the text area should span (works for both single line or multi line) size V1.5 none Synonym for ?cols? when using single-line (rows=1) input highlightcolor ? Ajax.InPlaceEditor.defaultHighlightColor The highlight color highlightendcolor ? ?#FFFFFF? The color which the highlight fades to savingClassName V1.5 ?inplaceeditor-saving? CSS class added to the element while displaying ?Saving?? (removed when server responds) formClass Name? V1.5 ?inplaceeditor-form? CSS class used for the in place edit form hoverClass Name? ? ? loadTextURL V1.5 null Will cause the text to be loaded from the server (useful if your text is actually textile and formatted on the server) loadingText V1.5 ?Loading?? If the loadText URL option is specified then this text is displayed while the text is being loaded from the server callback V1.5 function(form) {Form.serialize(form)} A function that will get executed just before the request is sent to the server, should return the parameters to be sent in the URL. Will get two parameters, the entire form and the value of the text control. submitOnBlur V1.6 ?false? This option if true will submit the in_place_edit form when the input tag loses focus. ajaxOptions V1.5 {} Options specified to all AJAX calls (loading and saving text), these options are passed through to the [...]

getElementById has no properties in Firefox

Wed, 6 Sep 2006 04:25:00 -0400

I have a register JSP page that contains a form with some input fields. I use the getElementById method to retrieve form values and post them through AJAX. It works very well in IE. But in Firefox, I get the following error:

document.getElementById("customers_name") has no properties

I reviewed the W3C's DOM specification carefully, and found the getElementById section.

getElementById introduced in DOM Level 2
Returns the Element that has an ID attribute with the given value. If no such element exists, this returns null.

I checked my code again and found that one of the input elements has no ID attribute. It is something like this:

When I assigned an ID attribute to the element, it works fine.

It appears that IE does not implement the DOM 2 Core and DOM 3 Core specifications correctly. It grabs form values based on the NAME attribute. While Firefox finds form elements by ID, when the input has no ID, null is returned. So, Firefox do the right thing.

Loading configuration files under WEB-INF/classes

Tue, 5 Sep 2006 09:32:00 -0400

We often need to load configuration files under WEB-INF/classes directory, it is usually a properties file or an XML file. There are many different ways of doing this. The method below can be used only in a non-static method.

public File getResource(String fileName) {
    URL url = this.getClass().getResource("/" + fileName);
    return url != null ? new File(url.getFile()): null;

When called in a static method, an error will occur:

non-static method XXX cannot be referenced from a static context

To find the absolute path of a file under WEB-INF/classes in a static method, I often use the following two solutions:

public static File getFileFromInputStream(String fileName) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource(fileName);
    if (url != null) {
        File file = new File(url.getFile());
        return file;
    } else {
        return null;


public class MailService {
    public static File getResource(String fileName) {
        URL url = MailService.class.getResource("/" + fileName);
        return url != null ? new File(url.getFile()): null;

Replacing line feeds with HTML breaks using JSTL

Mon, 4 Sep 2006 10:30:00 -0400

In my recent e-commerce web application, I use a textarea input element to gather reviews from our customers and store them in a database. The text user entered may contain line breaks (\n). When I retrieve the data and display it in a web page - the line breaks are ignored, and the result is pretty unreadable.

I first tried to replace these line breaks (\n) with html breaks (
) by using the following statement:

${fn:replace(reviewDB.review_text, "\n", "

However, I got the following exception:

/productdetail.jsp(268,14) "${fn:replace(reviewDB.review_text, "\n", "
")}" contains invalid expression(s): javax.servlet.jsp.el.ELException: Encountered ""\n", expected one of [, , , "true", "false", "null", "(", "-", "not", "!", "empty", ]

Finally, I found two solutions to achieve this work, the following is the first solution:

<%pageContext.setAttribute("linefeed", "\n"); %> ")}" escapeXml="false"/>

Another solution is using the Jakarta String Tag Library

<%@ taglib uri="" prefix="str" %> ${review.reviews_text}

Note that this solution also requires Commons Lang library, which can be downloaded at

Javascript Chaos Engine - a javascript scrambler / obfuscator

Thu, 10 Aug 2006 04:27:00 -0400

Javascript Chaos Engine Free Edition is a free of charge powerful javascript scrambler / javascript obfuscator. With this tool you will be able to keep your javascript source from prying eyes.

This tool converts your javascript identifiers to keys of variable length. The program let you choose what to scramble, what to leave unscrambled, take away all linefeeds and keeps non javascript code untouched.

It can be downloaded at

Integrate TinyFCK with JSP

Wed, 2 Aug 2006 09:40:00 -0400

Both FCKEditor and TinyMCE are powerful Web-based HTML text editors. They can be integrated into Content Management Systems easily. However, FCKEditor is too big, while TinyMCE lacks of a free file manager/uploader. Today, I found TinyFCK, as its name implies, it integrates the TinyMCE with FCKEditor's file manager. I've integrated it with jsp successfully. The following are my steps: Step 1 - Download 1. Download the tinyfck archive from 2. Download the FCKEditor JSP Integration Pack archive from Step 2 - Install 1. Unzip the tinyfck archive in a directory named "tinyfck" under your web application(For example, "WebApp/tinyfck"). 2. Unzip the FCKEditor Java Integration Library in a directory named "FCKeditor", and copy the two archive files "commons-fileupload.jar" and "FCKeditor-2.3.jar" under the web/WEB-INF/lib directory to your web application's WEB-INF/lib directory(For example, "WebApp/WEB-INF/"). The final directory structure should look similar to this: /WebApp/ /tinyfck /WEB-INF /lib Step 3 - Integrate Append the following servlet and mapping definitions to the WebApp/WEB-INF/web.xml file Connector com.fredck.FCKeditor.connector.ConnectorServlet baseDir /UserFiles/ debug true 1 SimpleUploader com.fredck.FCKeditor.uploader.SimpleUploaderServlet baseDir /UserFiles/ debug true enabled false AllowedExtensionsFile DeniedExtensionsFile php|php3|php5|phtml|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|dll|reg|cgi AllowedExtensionsImage jpg|gif|jpeg|png|bmp DeniedExtensionsImage AllowedExtensionsFlash swf|fla DeniedExtensionsFlash 1 Connector /tinyfck/filemanager/connectors/jsp/connector

Getting requestURI using JSTL

Tue, 1 Aug 2006 10:32:00 -0400

Just a simple note

    // do something here

Javascript debuggers

Tue, 1 Aug 2006 10:26:00 -0400

Along with the development of AJAX, it is necessary to get a handy javascript debugger. The following Javascript debuggers can make our life easier.

1. Venkman JavaScript Debugger - for Firefox

It provide a powerful JavaScript debugging environment for Mozilla based browsers, including Firefox 1.0.x, Firefox 1.5.x, the Netscape 7.x series of browsers and Mozilla Seamonkey 1.x.

The latest version is 0.9.87, which can be downloaded here:

2. FireBug - for Firefox

FireBug lets you explore the far corners of the DOM by keyboard or mouse. All of the tools you need to poke, prod, and monitor your JavaScript, CSS, HTML and Ajax are brought together into one seamless experience, including a debugger, an error console, command line, and a variety of fun inspectors.

 A quick overview of FireBug's features:

* JavaScript debugger for stepping through code one line at a time
* Status bar icon shows you when there is an error in a web page
* A console that shows errors from JavaScript and CSS
* Log messages from JavaScript in your web page to the console (bye bye "alert debugging")
* An JavaScript command line (no more "javascript:" in the URL bar)
* Spy on XMLHttpRequest traffic
* Inspect HTML source, computed style, events, layout and the DOM

It can be installed at

3. Microsoft Script Debugger - for IE

It allows developers to more efficiently and effectively develop script applications. Such as:

* View the source code of the script they are debugging.
* Control the pace of script execution with break points and stepping.
* View and change variable and property values with the Command Window.
* View and control script flow with the Call Stack Window.
It can be downloaded at:

Iterate over HashMap with JSTL

Fri, 21 Jul 2006 06:22:00 -0400

I've ever written a java bean base on Commons DBUtils, which returns an ArrayList of HashMap results from SQL query. The following is one of my Java Bean:

package database;
import java.util.ArrayList;
import java.util.List;
public class CategoryDBAO {
    public List getAllCategories() {
        ArrayList categoryList = new ArrayList();
        try {
            String sql = "select categories_id, categories_name from categories";
            attrList = DBConn.searchToMapList(sql);
        } catch (Exception e) {
        return categoryList;

Many times I need to iterate over the set of the values stored in the map. This can be done like this:

What should be noted here is the code fragment in red.

Adding a function to a dymanically created input element using javascript

Wed, 19 Jul 2006 20:46:00 -0400

I meet some trouble when adding a new script function to a dynamically created input element. The code is something like this:

var inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.setAttribute("id", "price");
inputElement.setAttribute("name", "price");
inputElement.setAttribute("value", "0");
inputElement.setAttribute("onkeypress", "return numeralsOnly(this.value, event, 2);"); = "90%";
inputElement.className = "text";

Everything works except the onkeypress function. After changing the code to the following, it works fine.

var inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.setAttribute("id", "price");
inputElement.setAttribute("name", "price");
inputElement.setAttribute("value", "0"); = "90%";
inputElement.className = "text";
var func = new Function("return numeralsOnly(this.value, event, 2);");
inputElement.onkeypress = func;

A free 10-week "AJAX Programming" online course

Sat, 15 Jul 2006 21:06:00 -0400

A free 10-week "AJAX Programming" online course is about to start from August 4th, 2006. This course is for anyone who wants to learn AJAX for the first time or increase their knowledge on AJAX. In this 10-week course, students learn basic concept of AJAX as well as how to use various AJAX frameworks and toolkits such as Dojo toolkit, jMaki, Google Web Toolkit, and AJAX-fied JavaServer Faces (JSF) components.

This course runs very much like a regular college course in which the students are expected to do weekly homeworks after studying the presentation material but it is free and can be taken online. There is also class group alias where students can ask/answer questions. The complete set of course contents (StarOffice slides with detailed speaker notes and flash demo files, hands-on labs, homework assignments, etc.) are available on the website of the course. The only thing you have to do in order to register for the course is sending an blank email to Unable to recognize OLE stream

Wed, 26 Apr 2006 09:38:00 -0400

I have been using JExcelAPI to import data from excel spreadsheets to database. For ease of use, I wrote a JavaBean named DataImport. However, it can not work recently. it always gives me the following exception: Unable to recognize OLE stream at at at jxl.Workbook.getWorkbook( at jxl.Workbook.getWorkbook( I first considered the problem was caused by Excel 2003. Because we used Excel 2000 originally, which uses the BIFF8 format, while excel XP and excel 2003 use BIFF8X format which is an extension of The BIFF8 format. However, when I imported an excel file created in excel2000, I got the same exception. I downloaded the source code of JExcelAPI, and found the code line throwing the exception // // First verify the OLE identifier for (int i = 0; i < IDENTIFIER.length; i++) { if (data[i] != IDENTIFIER[i]) { throw new BiffException(BiffException.unrecognizedOLEFile); } } The definition of IDENTIFIER can be found in /** * The identifier at the beginning of every OLE file */ protected static final byte[] IDENTIFIER = new byte[] {(byte) 0xd0, (byte) 0xcf, (byte) 0x11, (byte) 0xe0, (byte) 0xa1, (byte) 0xb1, (byte) 0x1a, (byte) 0xe1}; And then, I opened the excel file using UltraEdit in Hex mode 0 1 2 3 4 5 6 7 8 9 a b c d e f 00000000h: D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 ; ?.???....... 00000010h: 00 00 00 00 00 00 00 00 3E 00 03 00 FE FF 09 00 ; ........>...?.. 00000020h: 06 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 ; ................ 00000030h: 01 00 00 00 00 00 00 00 00 10 00 00 02 00 00 00 ; ................ 00000040h: 01 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00 ; ....? ........ As you can see, the first 8 bytes of the file is the same as the definition in So, it is not the problem of the excel file. I compared my code with the working one carefully, and found the root cause of the problem in the end. The excel file is uploaded using a multipart/form-data form. In the working one, there is only an input type="file" element in the form element. It is something like this:
Select file to import
While in the one throwing the exception, there are some other elements besides the file element:
Select table to import
Select file to import
And the following is the code snippet used to parse the input stream from the request. ServletInputStream is = request.getInputStream(); byte[] junk = new byte[1024]; int bytesRead = 0; // strip off the HTTP information from input stream // the first four lines are request junk bytesRead = is.readLine(junk, 0, junk.length); bytesRead = is.readLine(junk, 0, junk.length); bytesRead = is.readLine(junk, 0, junk.length); bytesRea[...]

getOutputStream() has already been called for this response

Mon, 17 Apr 2006 10:20:00 -0400

Today, When I export data from database to an excel file, I always get the following exception:

java.lang.IllegalStateException: getOutputStream() has already been called for this response
 at org.apache.catalina.connector.Response.getWriter(
 at org.apache.catalina.connector.ResponseFacade.getWriter(
 at org.apache.jasper.runtime.JspWriterImpl.initOut(
 at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(
 at org.apache.jasper.runtime.JspWriterImpl.write(
 at org.apache.jasper.runtime.JspWriterImpl.write(

Below is the code used to export the excel file:

response.setHeader("Content-Disposition","attachment; filename=report.xls");
exp.setColumnNames(new String[] {"id", "productname", "price", "inventory"});

I've tried all of the solutions found on the web, but no luck. Finally, I deployed my web application to Resin, I got another exception instead.

 at com.esurfer.freshetgis.DataExport.exportData(
 at _jsp._sjcl._duikouanzhi__jsp._jspService(
 at com.caucho.jsp.JavaPage.service(
 at com.caucho.jsp.Page.pageservice( 

According to the exception, I've checked my code over and again, and found the root cause of the problem. I've typed the wrong field name, the field "id" should be "pid". So when I retrieved data using map.get("id"). The code above will throw a NullPointerException. It seems that Tomcat gives the wrong error message. If you meet such a problem, and can't work it out by following the solutions found on the web, try another way. Do not be confused by the exception message you get.

Commons FileUpload exception when parsing the request

Mon, 17 Apr 2006 06:37:00 -0400

When I upload an excel file using Commons FileUpload, I got the following exception:

java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream

After googling the net, I found the solution. Commons FileUpload requires commons-io library. After I download the Commons IO library and put it in /WEB-INF/lib, the problem is solved.

Silent installation of JDK and JRE

Mon, 10 Apr 2006 11:36:00 -0400

I recently have the requirement to install JDK and JRE in silent mode. This can be done by running the JDK (or JRE) installer from the command line with additional parameters. 1. Install JDK in silent mode: .exe /s /v"/qn [ADDLOCAL=ToolsFeature[,DemosFeature][,SourceFeature] [INSTALLDIR=:\] [REBOOT=Suppress]" where.exe is the single executable installer for the Java 2 SDK; ADDLOCAL, if used, is either ToolsFeature[,DemosFeature][,SourceFeature]; INSTALLDIR, if used, specifies the drive and path of the installation; and REBOOT=Suppress, if used, indicates that if locked files are encountered the computer should not be rebooted.If ADDLOCAL=ToolsFeature[,DemosFeature][,SourceFeature] is used,ToolsFeature indicates the tools of the J2SDK will be installed;DemosFeature (optional) indicates that the J2SDK demos will be installed;SourceFeature (optional) indicates that the file including the j2sdk source will be installed.If ADDLOCAL is not used, then all of the features will be installed.If INSTALLDIR is not specified, the installation will go into [WindowsVolume]:Program Files\j2sdk1.5.0 (default location). Example: jdk.exe /s /v"/qn ADDLOCAL=ToolsFeature INSTALLDIR=d:\jdk\jdk15" 2. Install JRE in silent mode: .exe [/L] /s /v"/qn [ADDLOCAL=jrecore[,extra][,other_US] | ALL] [IEXPLORER=1] [MOZILLA=1] [INSTALLDIR=:\] [REBOOT=Suppress] [JAVAUPDATE=0] [CUSTOM=1]" where.exe is the single executable installer for the Java Runtime Environment (JRE); /L, if used, sets the localized language for the installer (see language IDs); ADDLOCAL, if used, is either jrecore[,extra][,other_US] or ALL; IEXPLORER=1, if used, indicates that the Plug-in should be registered with the Internet Explorer browser; MOZILLA=1 indicates that the Plug-in should be registered with Mozilla 1.1 and later and Netscape browsers (for releases prior to 5.0, see note above); INSTALLDIR, if used, specifies the drive and path of the installation; REBOOT=Suppress, if used, indicates that if locked files are encountered the computer should not be rebooted; JAVAUPDATE=0, if used, indicates that the Java Update feature should be disabled (the Update tab in the Java Control Panel will not appear); and if CUSTOM=1 is used, the user will only see the license agreement, which must be accepted, and the progress bar.If ADDLOCAL=jrecore[,extra][,other_US] is used,jrecore indicates the core of the JRE will be installed;extra (optional) indicates additional Fonts, Colors, and Soundbank will be installed;other (optional) indicates locale-specific .jar files will be installed.If ADDLOCAL=ALL is used, then all the features will be installed.If ADDLOCAL is not used, then only the recommended features will be installed: jrecore will be installed; extra will not be installed; other will be installed only if l10n support, other than English, is installed.If INSTALLDIR is not specified, the installation will go into C:\Program Files\java\jre1.5.0 (default location). Example: jre.exe /s /v"/qn ADDLOCAL=ALL IEXPLORER=1 INSTALLDIR=D:\jdk\jre" It should be note that the command is case sensitive and there must be no spaces in the features listed with ADDLOCAL. And the command line examples above is for Windows Offline Installation only, no space should appear between the /v and the quote ("). For more information, visit: http://jav[...]

Improve the performance of Netbeans

Tue, 21 Mar 2006 07:02:00 -0500

I'm running Netbeans 5.0 with JDK 1.5.0_06 on Windows XP. It is getting more and more slow, especially during the garbage collection. I found some tunning tips on the NetBeans site. 1. Disable the modules that you don't use. With NetBeans 5.x use Tools | Module Manager to display a dialog allowing you to configure modules. 2. Try switching to a different garbage collection algorithm and tunning JVM switches. This can be done by setting the following options in the configuration file $NB_HOME/etc/netbeans.conf. -J-Xverify:none - this switch turns off Java bytecode verification, making classloading faster, and eliminating the need for classes to be loaded during startup solely for the purposes of verification. This switch improves startup time, and there is no reason not to use it. -J-Xms32m - this setting tells the Java virtual machine to set its initial heap size to 32 megabytes. By telling the JVM how much memory it should initially allocate for the heap, we save it growing the heap as NetBeans consumes more memory. This switch improves startup time. It is used by default in NetBeans, so you do not need to specify it. -J-Xmx256m - this settings tells the Java virtual machine the maximum amount of memory it should use for the heap. Placing a hard upper limit on this number means that the Java process cannot consume more memory than physical RAM available. This limit can be raised on systems with more memory. Current default value is 128MB. Note: Do not set this value to near or greater than the amount of physical RAM in your system or it will cause severe swapping during runtime. On machines with limited memory (less than 384MB), it is recommended that you set the initial heap size lower than the default. Open the configuration file etc/netbeans.conf in a text editor and modify the options in netbeans_default_options setting. Decrease the option -J-Xmx128m to -J-Xmx96m and the option -J-XX:MaxPermSize=96m to -J-XX:MaxPermSize=64m. -J-XX:+UseConcMarkSweepGC or -J-XX:+UseParNewGC - try these switches if you are having problems with intrusive garbage collection pauses. This switch causes the JVM to use different algorithms for major garbage collection events (also for minor collections, if run on a multiprocessor workstation), ones which do not "stop the world" for the entire garbage collection process. You should also add the line -J-XX:+CMSClassUnloadingEnabled and -J-XX:+CMSPermGenSweepingEnabled to your netbeans.conf file so that class unloading is enabled (it isn't by default when using this collector). -XX:+UseAdaptiveSizePolicy - this switch may help improve garbage collector throughput and memory footprint. It is part of garbage collector ergonomics implemented in JDK5.0. -J-XX:+UseParallelGC - some tests have shown that, at least on systems fairly well equipped with memory, the durations of minor garbage collections is halved when using this collection algorithm, on uniprocessor systems. Note that this is paradoxical - this collector is designed to work best on multiprocessor systems with gigabyte heaps. No data is available on its effect on major garbage collections. Note: this collector is mutually exclusive with -J-XX:+UseConcMarkSweepGC. -J-XX:CompileThreshold=100 - this switch will make startup time slower, by HotSpot to compile many more methods down to native code sooner than it otherwise would. The reported result is snappier performance once the IDE is running, since more of the UI code will be compiled rather[...]

Precompile JSP files in Netbeans

Wed, 15 Mar 2006 08:10:00 -0500

Quite often we may need to precompile jsp files to get better performance without waiting the first time hit, or protect our jsp code by only shipping the corresponding CLASS files. Some JSP containers support the capability of precompiling a JSP page by accessing the jsp page with a query string of ?jsp_precompile: Netbeans IDE also implements the jsp compilation. Just right click a single jsp file and choose compile file or select the "Test compile all JSP files during builds" checkbox (in the Compiling panel of the Project Properties dialog box). However, we must define explicit servlet mappings for each servlet in our Web application manually. It is a hard work. Fortunately, the Netbeans-generated build file provides several targets which are by default empty and can be used for execution of customized tasks. They are: -pre-init: called before initialization of project properties -post-init: called after initialization of project properties -pre-compile: called before javac compilation -post-compile: called after javac compilation -pre-compile-single: called before javac compilation of single file -post-compile-single: called after javac compilation of single file -pre-compile-test: called before javac compilation of JUnit tests -post-compile-test: called after javac compilation of JUnit tests -pre-compile-test-single: called before javac compilation of single JUnit test -post-compile-test-single: called after javac compilation of single JUunit test -pre-dist: called before jar building -post-dist: called after jar building -post-clean: called after cleaning build products I've created one build script used to precompile jsp files by using Tomcat JspC task. It is something like this: Precompile JSP files

Creating AJAX and Rich Internet Components with JSF - Part 2

Sun, 26 Feb 2006 07:17:00 -0500

Creating AJAX and Rich Internet Components with JSF - Part 2 ? In our previous article - 'Rich Internet Components with JavaServer Faces' (JDJ, Vol. 10, issue 11) - we discussed how JavaServer Faces can fulfill new presentation requirements without sacrificing application developer productivity building Rich Internet Applications (RIA). We discussed how JSF component writers can utilize technologies, such as AJAX and Mozilla XUL, to provide application developers with rich, interactive, and reusable components.

Creating AJAX and Rich Internet Components with JSF - Part 1

Sun, 26 Feb 2006 07:16:00 -0500

Creating AJAX and Rich Internet Components with JSF - Part 1 ? JavaServer Faces (JSF) standardizes the server-side component model for Web application development but doesn't standardize the presentation layer at the browser. In a series of articles we are going to look at how JSF can fulfill new presentation requirements without sacrificing application developer productivity building Rich Internet Applications (RIA). AJAX has gained momentum primarily due to the XMLHttpRequest browser object, which supports asynchronous communication with any business services used by the Web application. Popular sites such as Google Mail and Google Suggest use AJAX to deliver RIA.

AJAX based Google Page Creator

Sun, 26 Feb 2006 07:01:00 -0500

Google has launched a new exciting AJAX based product - Google Page Creator. It is a free tool that lets us create web pages online through browser and publish them to web space hosted on Google servers with one click. We can create more pages and change the look and the layout of them. When these pages are ready, we can publish them. These pages can be visited at In addition, Google provides up to 100MB of space for web pages and uploaded files.
To use Google Page Creator, you must have a Gmail account. Visit for more information.

Master index of the NetBeans tutorials

Fri, 24 Feb 2006 09:21:00 -0500

Sang Shin maintains a master index of NetBeans tutorials and articles which can be visited at Thanks a lot for his excellent work!

Close an IE window without prompt

Fri, 3 Feb 2006 10:40:00 -0500

Usually, we need to close an IE window without prompt, the code below can achieve this.

Gathering form data for AJAX posting

Thu, 2 Feb 2006 03:05:00 -0500

When migrating an existing application to AJAX-based technologies, we need to make some change the exising code. For example, to submit a form, the code maybe changed to: function add2Cart(frmObj) {    var url = "shopping.jsp";    var data = "productid=" + frmObj.productid.value + "&amount=" + frmObj.amount.value + "&price=" + frmObj.price.value;    xmlhttp.onreadystatechange = handler;"POST", url, true);    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");    xmlhttp.send(data);} function handler() {      if (xmlhttp.readyState == 4) {         if ( xmlhttp.status == 200) {            alert("success");         } else {            alert('failed");         }      }} However, it is horrible to change the code like above. The following javascript function can be used to gether form data. function getFormValues(obj) {    var queryStr = "";    for (i = 0; i < obj.childNodes.length; i++) {        if (obj.childNodes[i].tagName == "input") {            if (obj.childNodes[i].type == "text" || obj.childNodes[i].type == "hidden") {               queryStr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";            }            if (obj.childNodes[i].type == "checkbox") {               if (obj.childNodes[i].checked) {                  queryStr += obj.childNodes[i].name + "=" + obj.childNodes [i].value + "&";               } else {                  queryStr += obj.childNodes[i].name + "=&";               }            }            if (obj.childNodes[i].type == "radio") {               if (obj.childNodes[i].checked) {                  queryStr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";               }            }        }          if (obj.childNodes[[...]

Xerces parser error in applet

Fri, 27 Jan 2006 10:36:35 -0500

I'm using Mapxtreme for Java 4.7.1 with JDK 1.5 and Tomcat 5.5.7 on Windows 2000 Server and I developed a mapxtreme for java applet, in this applet I defined two public methods. One is used to create the contour annotation layer, the other is used to search the point features covered by the region on the contour layer. This applet runs perfectly in applet viewer. However, when I invoked the second method using javascript in jsp page, I got the following exception:

java.lang.RuntimeException: org.jdom.JDOMException: Could not load org.apache.xerces.parsers.SAXParser: SAX2 driver class org.apache.xerces.parsers.SAXParser not found: org/apache/xerces/parsers/SAXParser
 at Source)
 at Source)
 at Source)
 at Source)
 at Source)
 at com.mapinfo.dp.util.RewindableFeatureSet.getNextFeature(Unknown Source)
 at SimpleMap.drawContour(
 at SimpleMap.contour(
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
 at Source)
 at Source)
 at$ Source)
 at Method)
 at Source)

I thought it must be the problem of classloader. I tried to put the jar files xercexImpl.jar, xml-apis.jar, jdom.jar, xalan.jar in all of the following directories:

Applet directory

But no luck. Finally, I found the solution at the Apache Xerces site. Just create a directory named "endorsed" under JRE/lib directory and copy the jar file "xercesImpl.jar" to this directory. This operation is to override the JAXP implementation in JDK1.4 and above. However, Putting this JAR to another location like lib/ext WILL NOT WORK. After doing this, my applet works fine. You can visit for more information.

Here, I also want to thank Roel De Nijs for his kindly help!

Unable to load php_mysql.dll

Wed, 18 Jan 2006 08:34:00 -0500

When configuring apache 2.0.55 with php 5.0.4 on Windows Server 2003, I got the error message: ?PHP Startup: Unable to load dynamic library ?D:\Apache2\php\ext\php_mysql.dll? - The specified module could not be found.? To make it work, just copy the libmysql.dll come with the PHP distribution into c:\windows\system32.

6-week Java Intro Programming Online Bootcamp has already begun

Mon, 16 Jan 2006 21:54:00 -0500

The free "6-week Java Intro Programming Online Bootcamp" course taught by Sang Shin has already begun from Jan. 16th, 2006. This bootcamp is for anyone who wants to learn Java programming for the first time.  In this course, students will learn how to write, compile, and run Java programs. They will also learn essential object oriented programming concepts such as inheritance and polymorphism. Students will write and run the Java programs using both command line tools and NetBeans IDE.

Each week, students are expected to do weekly homework after studying the presentation and hands-on lab material. There is also class group alias where students can ask questions.

The only thing you have to do in order to register for the course is sending an email to the following address.

For detailed information about this bootcamp, please go to the following websites.

  Course website:
  Course schedule:
  Course group alias:

AJAX caching problem

Thu, 1 Dec 2005 09:57:35 -0500

People all over the internet are talking about the hottest buzzword - AJAX (or Asynchronous JavaScript and XML). As we already know, it is not a technology in itself, but a term that refers to the use of a combination of technologies to create interactive web applications, including HTML (or XHTML) and CSS, DOM, the XMLHttpRequest object. Now we can see some excellent applications using AJAX such as Google Maps. I also use it in my online exam project. The following are the code: xmlhttp, which used to create the XMLHttpRequest Object function getHTTPObject() {      var xmlhttp;      /*@cc_on @*/      /*@if (@_jscript_version >= 5)             try {                 xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")             } catch (e) {                 try {                     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")                 } catch (E) {                     xmlhttp=false                 }           }      @else           xmlhttp=false      @end @*/      if (!xmlhttp && typeof XMLHttpRequest!='undefined') {           try {                xmlhttp = new XMLHttpRequest();           } catch (e) {                xmlhttp=false           }      }      return xmlhttp;}var xmlhttp = getHTTPObject(); The function below communicate with JSP and return the result of the operation function makePaper(planid, roomid) {  var url = "makepaper.jsp?planid=" + planid + "&roomid=" + roomid;"GET", url, true);  xmlhttp.onreadystatechange = function() {   if (xmlhttp.readyState == 4) {    result = xmlhttp.responseText;    if (result == 'success') {        alert("Success!");    } else {        alert("Failed!");    }   }  }  xmlhttp.send(null);  return false;} The server side JSP is something like this: <%@page pageEncodi[...]

Form post using Ajax

Thu, 1 Dec 2005 09:48:00 -0500

Ajax becomes increasingly popular as a new approach to create rich client web applications. By using Ajax we can submit form data to web server in the background asynchronously. I've been using Ajax in many projects. Such as changing the content of select elements dynamically, creating auto-completion text field etc. However, I came across some trouble in my recent instant message system base-on Ajax. I want to send messages using Ajax when users press the ctrl and enter key. When I sent Chinese characters, I got ???. I tried to encode the message using encodeURIComponent(), as well as encode the entire URL using encodeURI, but no luck. Finally, I solved the problem by using post method and utf-8 encoding. The following code snippet is used to send messages:

In the send.jsp page, we can retrieve the message from request parameter directly without setting the character encoding. It is something like this:

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" 
%><%@page import="platform.*, java.util.*" 
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "no-store");
String sender = request.getParameter("sender");
if (sender == null) sender = "";
String receiver = request.getParameter("receiver");
if (receiver == null) receiver = "";
String message = request.getParameter("message");
if (message == null) message = "";
// save message into database

And the following are some excellent articles about submitting form using Ajax:


There is also a new book - Ajax In Action which shows how to design Ajax apps and teaches numerous Ajax implementation techniques. You can visit manning's site for more information.

Automatically load a page after a few seconds

Tue, 15 Nov 2005 07:55:40 -0500

We've developed a high load online exam system in which instructors create exams and deliver them through browser. The questions on the paper is randomly chose based on the parameters specified by the instructor. When students are ready to take the exam, the paper for each student will be sent to the browser from the server. I've created two paper pages. One is used to display the empty paper when the student login the first time. The other is used to display the paper with the answers the student already entered when he exit the system abnormally while taking an exam, he can simply re-connect, go back to the exam, and resume the exam. On an average we have about 50 to 100 students taking tests concurrently. Sometimes, one or two machines cannot fetch the paper page successfully. Instead an error page is displayed. If the student then hit the refresh button the page is displayed. I want to direct the student to a friendly error page with this message: 'The server is busy now, you will be redirected to the paper page after 5 seconds.', and then reload the paper page automatically, instead of telling the students to refresh the page manually. However, as I mentioned above, there are two paper pages, both can throw the exception. So I must know which page throw the exception. I first thought of using request.getHeader("Referer") to get it, but it is always null. Finally, I added an additional parameter to the custom error page in the page directive, which is used to tell the error page which paper page throws the exception. In the error page, I can fetch the parameter from the request, and then set the "Refresh" header to redirect the student to the paper page which throws the exception. In order to verify my idea, I write the following test code: // the web page throws the exception, exception.jsp <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %><%@ page errorPage="retry.jsp?from=exception.jsp" %><%response.setHeader("Pragma", "no-cache");response.setHeader("Expires", "0");response.setHeader("Cache-Control", "no-store");%>

Exception Testing

<%String test = request.getParameter("id");out.println(Integer.parseInt(test));%> // error handler page, retry.jsp <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %><%@ page isErrorPage="true" %><%String from = request.getParameter("from");response.setHeader("Refresh", "5; URL=" + from);%>
  The server is busy now, you will be redirected to the paper page after 5 seconds.
  Click here if your page doesn't automatically refresh after 5 seconds.
As you can see, I also set the cache control headers in order to avoid the brow[...]

Formatting date retrieved from database

Mon, 7 Nov 2005 20:30:14 -0500

While getting the value of the date column from table using ResultSet.getString, I always get the date in the format: 2005-11-07 00:00:00.0. In order to display it in the format 'YYYY-MM-DD', I've tried two solutions:

1. Use ResultSet.getTimestamp to retrieve the value as a java.sql.Timestamp or ResultSet.getDate to get the value as a java.sql.Date. and then use SimpleDateFormat to format the result for display:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String orderdate = df.format(rs.getDate("orderdate"));

2. Use the ResultSet.getString to retrieve the value as a String and parse the date string into a Date object, and the format the result for display:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"); String orderdate = df1.format(df.parse(rs.getString("orderdate"));

Both solutions work well.

Get SQLNestedException again

Sat, 5 Nov 2005 02:54:18 -0500

When I configured SQL Server connection pool in Tomcat 5.5.9, I got the SQLNestedException again. org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource( at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection( at org.apache.commons.dbutils.QueryRunner.prepareConnection( at org.apache.commons.dbutils.QueryRunner.query( at org.apache.commons.dbutils.QueryRunner.query( at com.homesoft.db.DBConn.searchToMapList( at platform.Employee.getEmployeeList( at org.apache.jsp.newtask_jsp._jspService(org.apache.jsp.newtask_jsp:110) at org.apache.jasper.runtime.HttpJspBase.service( at javax.servlet.http.HttpServlet.service( at org.apache.jasper.servlet.JspServletWrapper.service( at org.apache.jasper.servlet.JspServlet.serviceJspFile( at org.apache.jasper.servlet.JspServlet.service( at javax.servlet.http.HttpServlet.service( at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter( at org.apache.catalina.core.ApplicationFilterChain.doFilter( at org.apache.catalina.core.StandardWrapperValve.invoke( at org.apache.catalina.core.StandardContextValve.invoke( at org.apache.catalina.core.StandardHostValve.invoke( at org.apache.catalina.valves.ErrorReportValve.invoke( at org.apache.catalina.core.StandardEngineValve.invoke( at org.apache.catalina.connector.CoyoteAdapter.service( at org.apache.coyote.http11.Http11Processor.process( at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection( at at at org.apache.tomcat.util.threads.ThreadPool$ at Source) Caused by: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getDriver(Unknown Source) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource( ... 27 more I reviewed my configuration again and again, but can't find out the reason. The following is the JNDI DataSource configuration in Tomcat server.xml file:    

MySQL Data truncation Error

Thu, 27 Oct 2005 10:23:25 -0400

When I recently upgraded to MySQL 4.1.10 and Connector/J 3.1.8, I got the following Exception: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data truncated for column 'productid' at row 1 In most cases, the exception is raised in the following two situtations: 1. The auto increment field is incremented using ''. 2. The date column is updated using ''. In order to recreate the problem, I created two tables, named "product" and "orders".  The former is used to test the auto increment field, the latter is used to test the date filed. CREATE TABLE `product` (  `productid` int(10) NOT NULL auto_increment,  `productname` varchar(50) NOT NULL default '',  `price` decimal(10,2) NOT NULL default '0.00',  PRIMARY KEY  (`productid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `orders` (  `orderno` int(10) NOT NULL default '0',  `orderdate` date default NULL,  PRIMARY KEY  (`orderno`)) ENGINE=InnoDB DEFAULT CHARSET=utf8; The following is the result of my test run from the mysql command line interface. mysql> insert into product values('', 'test', 100.00);Query OK, 1 row affected, 1 warning (0.36 sec) mysql> show warnings;+---------+------+------------------------------------------------+| Level   | Code | Message                                        |+---------+------+------------------------------------------------+| Warning | 1265 | Data truncated for column 'productid' at row 1 |+---------+------+------------------------------------------------+1 row in set (0.00 sec) mysql> insert into product values(null, 'test again', 20.00);Query OK, 1 row affected (0.05 sec) mysql> insert into orders values(1, '');Query OK, 1 row affected, 1 warning (0.05 sec) mysql> show warnings;+---------+------+------------------------------------------------+| Level   | Code | Message                                        |+---------+------+------------------------------------------------+| Warning | 1265 | Data truncated for column 'orderdate' at row 1 |+---------+------+------------------------------------------------+1 row in set (0.00 sec) mysql> insert into orders values(2, null);Query OK, 1 row affected (0.05 sec) As you can see, when I changed the insert statement from insert('', ... ) to insert(null, ...), it didn't generate a warning. Finally, I found that the problem was already mentioned in the Connector/J documentation: Prior to MySQL-4.1, the server itself couldn't report truncation of values. Starting with Connector/J 3.1.0, the JDBC driver will issue warnings or throw DataTruncation exceptions as is required by the JDBC specification[...]

Free Web Services Programming course

Sat, 15 Oct 2005 09:49:32 -0400

A free online "Web Services Programming" course is about to begin on Oct. 26th, 2005 for anyone who wants to learn Web services programming. In this 13-week course, attendees learn basic Web Services standards such as SOAP and WSDL, and Java API's for Web services such as JAX-WS, SAAJ, and JAXR. The principles of SOA and relevant technologies such as JBI and BPEL are also addressed. They also learn how to use NetBeans IDE effectively for building and deploying Web services.

This course runs very much like a regular college course in which the attendees are expected to do weekly homework and final project but it is free and can be taken online.  There is also class group alias where attendees can ask/answer questions. The complete set of course contents (StarOffice slides with detailed speaker notes and some audio files, homework assignments, reading materials, code samples, FAQ etc.) are available on the website of the course.

The only thing you have to do in order to join the course is sending an email to

For detailed information about this course, please go to the following class website.

  Course website:
  Course schedule:
  Course group alias:

Implement pagination using BETWEEN/AND

Sun, 2 Oct 2005 05:25:55 -0400

I've signed an account at It provides HSQLDB database services. The version of HSQLDB is 1.61. My problem comes here. I want to break up the resultsets retrieved from database into multiple pages, each page only displays specified subset of rows. However, One limitation of HSQLDB 1.61 is that it does not support LIMIT clause in the SELECT statement like MySQL. On the other hand, I don't want to use pagination taglibs. I've been searching the solution for a long time, but no luck. Finally, I implemented the pagination using BETWEEN and AND sql clause. This paging solution assumes that the table must have a primary key. In my example, I will create a table called bookmarks with the primary key id as follows: CREATE TABLE BOOKMARKS( ID INTEGER PRIMARY KEY, NAME VARCHAR, URL VARCHAR, DESCRIPTION VARCHAR ) The pagination approach will be something like this: // the first page SELECT * FROM bookmarks WHERE id BETWEEN 1 AND 10 // the second page SELECT * FROM bookmarks WHERE id BETWEEN 11 AND 20 To implement the pagination, I will use four variables: numofrec - the total number of records recPerPage - the number of rows per page pageno - the page number url - the page URL The variables numofrec and pageno will be appended to request parameters of the page when generating the page index. It will be something like this: pagination.jsp?pageno=5&numofrec=1000 (without other parameters in the page URL) or pagination.jsp?otherparam=value&pageno=5&numofrec=1000 (with other parameters in the page URL) When the page is requested the first time, count the total number of records and save the value into a variable. As I mentioned above, this value will be appended to the request parameter called numofrec, When the page number is greater than 1, the total number of records will be retrieved directly from this request parameter instead of count it again. if (iPageNo == 1) { rs = stat.executeQuery("SELECT COUNT(id) AS cnt FROM bookmarks"); if ( && rs.getString(1) != null) { numOfRec = Integer.parseInt(rs.getString(1)); } } The next work is to find out the lowest primary key and highest primary key according to the current page number. These two values will be assigned to the parameters of the following sql statement: SELECT * FROM bookmarks WHERE id BETWEEN ? AND ? To achieved this, first count the start index to retrieve the lowest primary key, then offset the cursor away from the start index by the recperpage amount, and retrieve the highest primary key: int iFrom = (iPageNo - 1) * recPerPage + 1; int iOffset = recPerPage - 1; if ( (iFrom + iOffset) > numOfRec ) iOffset = numOfRec - iFrom; rs = stat.executeQuery("SELECT id FROM bookmarks ORDER BY id"); rs.relative(iFrom); String sLowestId = rs.getString(1); rs.relative(iOffset); String sHighestId = rs.getString(1); In order to improve the performance, I limit the number of rows returned for the query used to retrieve the l[...]

Open a new window maximized

Fri, 30 Sep 2005 05:23:47 -0400

Just a javascript function used to open a new window maximized:

function openwindow(url) {
    var options = 'scrollbars=yes,resizable=yes,status=no,toolbar=no,menubar=no,location=no';
    options += ',width=' + screen.availWidth + ',height=' + screen.availHeight;
    options += ',screenX=0,screenY=0,top=0,left=0';
    var win =, '', options);
    win.moveTo(0, 0);
    win.resizeTo(screen.availWidth, screen.availHeight);

Advanced syntax highlighting tool

Thu, 22 Sep 2005 12:08:12 -0400

I often need to post code snippet to my weblog. Today I found the Advanced Syntax Highlighting tool provided by It can be used to generate HTML output of source code. Using it is very easy. Just copy and paste the code and click the Highlight button, and then copy the result HTML to weblog editor. This tool supports many languages, including PHP, HTML, Java, C, C++, ASP etc. also provides other useful webmaster tools that can be found at:

Compressing web content with GZip and Filter

Wed, 7 Sep 2005 04:01:25 -0400

I come across some performence problems in my recent j2ee web project. It always takes a long time for the visitors to wait to see the whole web page. Most of the web content is text-based. So I decide to compress the web content using gzip, which can dramatically reduce download times for text-based files. This can be done in a Filter. First, check whether a browser supports gzip compression. Browsers that support this feature will set the Accept-Encoding request header. /** Does the client support gzip? */public boolean isGzipSupported(HttpServletRequest request) {    String encodings = request.getHeader("Accept-Encoding"); return ((encodings != null) && (encodings.indexOf("gzip") != -1));} If a browser supports gzip, we can then send gzip-compressed content to it. The following is the whole code: package com.esurfer.filters; import;import;import; import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class GzipFilter implements Filter { private FilterConfig config;  public GzipFilter() { }  public void init(FilterConfig filterConfig) throws ServletException {  this.config = filterConfig; }  public void doFilter(ServletRequest request, ServletResponse response,   FilterChain chain) throws IOException, ServletException {        // If the browser supports gzip, send compressed content.  // otherwise send the web content directly.  PrintWriter out;  if (isGzipSupported((HttpServletRequest) request)) {   out = getGzipWriter((HttpServletResponse) response);   ((HttpServletResponse) response).setHeader("Content-Encoding",     "gzip");   ResponseWrapper wrapper = new ResponseWrapper(     (HttpServletResponse) response);   chain.doFilter(request, wrapper);   out.print(wrapper.toString());   out.close();  } else {   chain.doFilter(request, response);  }  }  public void destroy() {  config = null; }  /** Check the Accepting-Encoding header from the HTTP request. */ public boolean isGzipSupported(HttpServletRequest request) {  String encodings = request.getHeader("Accept-Encoding");  return ((encodings != null) && (encodings.indexOf("gzip") != -1)); }  /** Return gzipping PrintWriter for response. */ public PrintWriter getGzipWriter(HttpServletResponse response) [...]

Select all the checkboxes in a form

Mon, 5 Sep 2005 00:25:44 -0400

The following two JavaScript functions can be used to quickly select or unselect all the checkboxes in a form. The first one applies to a group of checkboxes with the same name: function setCheckboxesByName(the_form, elts_name, do_check) {    var elts = document.forms[the_form].elements[elts_name];    var elts_cnt  = (typeof(elts.length) != 'undefined')                  ? elts.length                  : 0; if (elts_cnt) {        for (var i = 0; i < elts_cnt; i++) {            elts[i].checked = do_check;        }     } else {        elts.checked = do_check;    }} The second one applies to checkboxes with different names: function setCheckboxesByType(do_check) {    var elts = document.getElementsByTagName("input");    var elts_cnt  = (typeof(elts.length) != 'undefined')                  ? elts.length                  : 0; if (elts_cnt) {        for (var i = 0; i < elts_cnt; i++) {            if (elts[i].type == "checkbox") {                elts[i].checked = do_check;            }        }     } else {        if (elts.type == "checkbox") {            elts.checked = do_check;        }    }} Example code below: // Select or unselect checkboxes with the same name Select all checkboxes in a form