JDev

jstl, javaAugust 31, 2006 7:50 pm

There is a problem with using JSTL to show text data that was previously saved from a textarea. If you show such text data in a table, the line-breaks from the textarea will be ignored and the text will be hard to read. A possible solution is to use a Java bean to process such data and replace line-breaks with BR tags before showing it on the page. Such a bean may look as follows:

package beans;
public class HTMLBreaker {
   
    private String text;  
    public HTMLBreaker() {               
    } 
   
    private  String insertBreaks(String text){      
        int len = text.length();      
        StringBuffer sb = new StringBuffer(len+16);          
        for(int i=0; i<text.length();i++){       
            if(text.charAt(i)==’\n’)           
                sb.append("<br>");           
            else       
                sb.append(text.charAt(i));   
        }           
        return sb.toString();       
    }   
   
   
    public String getText() {
        return text;
    }

    public void setText(String string) {
         text="";
        if(string != null)
            text = insertBreaks(string);         
    }
}

 

Then, on a JSP page create  the bean instance:

    <jsp:useBean id=’hbreaker’ class=’beans.HTMLBreaker’>

Set the bean property with the value of a database field: 

     <c:set target=’${hbreaker}’ property=’text’ value=’${row.text}’/>

Display the modified value of the bean property on the page:  

   <jsp:getProperty name=’hbreaker’ property=’text’/>          

If you use the JSTL c:out tag:

<c:out value=’${hbreaker.text}’/>

the BR tags surrounding symbols will be replaced with HTML characters, and show up as such on the screen.                                       

Don’t forget to close the bean tag:

  </jsp:useBean> 

A couple of other solutions using the JSTL fn:replace function and the Jakarta String Tag Library are offered at this weblog.

 

Code, jstl 2:03 pm

This web page has a concise description of how to set and access java bean properties from JSTL.

Briefly, to initialize a bean and set its properties, use the following example:

<jsp:useBean id=’beanIdclass=’className’>
    <c:set target=’${beanId}’ property=’propName’ value=’${someValue}’/>
</jsp:useBean>

To get a bean property value:

    <c:out value=’${beanId.propName}’/>

Code, jstlAugust 30, 2006 12:39 pm

After you execute a JSTL query, the result set is assigned to the scoped var variable as an instance of the javax.servlet.jsp.jstl.sql.Result interface. This object provides properties for accessing the rows, column names, and size of the query’s result set:

Property Description
rows An array of SortedMap objects, each of which maps column names to a single row in the result set
rowsByIndex An array of arrays, each corresponding to a single row in the result set
columnNames An array of strings naming the columns in the result set, in the same order as used for the rowsByIndex property
rowCount The total number of rows in the query result
limitedByMaxRows True if the query was limited by the value of the maxRows attribute

Some usage examples as requested in the first comment to the blog:

First of all, you have to set up a data source, e.g. to connect to an Oracle database:

    <sql:setDataSource var="dataSrc"
       url="jdbc:oracle:thin:@127.0.0.1:1521:database_name"
       driver="oracle.jdbc.driver.OracleDriver"
       user="user_name" password="pass_word"/>

Then you run a query:

   <sql:query var="queryResults" dataSource="${dataSrc}">

        select system_id, employeename from employees

   </sql:query>
 Then, you display the results on the web page:

<table>
     <tr>
       <th>ID</th>
       <th>Name</th>
     </tr>
   <c:forEach var="row" items="${queryResults.rows}">
     <tr>    
       <td>   
          <c:out value="${row.system_id}"/>
       </td>
       <td><c:out value="${row.employeename}"/></td>
     </tr>
   </c:forEach>    
   </table>
 

This is as simple an example as you can get. The bottom line is that when you use the rows property, you refer to values by column names.

Here is an example that uses rowsByIndex property:

<c:forEach var="row" items="${queryResults.rowsByIndex}">
   <tr>    
       <td>   
          <c:out value="${row[0]}"/>
       </td>
       <td><c:out value="${row[1]}"/></td>
     </tr>
</c:forEach>     
 
Same resultset, you just refer to column values by the column index property.
   
The next example shows how to use the columnNames property:
      
<table>
     <tr>
       <th><c:out value="${queryResults.columnNames[0]}"/></th>
       <th><c:out value="${queryResults.columnNames[1]}"/></th>
     </tr>
    …
   </table>
    
 In this case, the table headings will be  system_id and employeename.
 
 The rowCount property is self-evident. It shows the number of rows returned by your query:

          <c:out value="${queryResults.rowCount}"/>

  
 You use the limitedByMaxRows property if you used the maxRows attribute in your query:
 
<sql:query var="queryResults" dataSource="${dataSrc}"
                    maxRows="20">
In this case, the resultset will contain only 20 rows.              

 <c:if test="${queryResults.limitedByMaxRows}">
                Your query returned too many rows.
</c:if>

   The limitedByMaxRows propery can be used for pagination purposes.
  

Now, I will show how to get to display a resultset from any sql statement. The resulting table will display field names as column headings. This code is pretty generic.

    <table>      
     <tr>
         <c:forEach var="columnName" items="${queryResults.columnNames}">
            <th><c:out value="${columnName}"/></th>
          </c:forEach>
      </tr>
    <c:forEach var="row" items="${queryResults.rows}">
          <tr>
              <c:forEach var="columnName" items="${queryResults.columnNames}">
                <td><c:out value="${row[columnName]}"/></td>
             </c:forEach>           
         </tr>
     </c:forEach>     
    </table>      

Visit this page to learn how to display and sort request parameters with  JSTL.

javascriptAugust 29, 2006 12:25 pm

I have looked through Simon Willison’s Re-Introduction to JavaScript several times, and have found this apt explanation of the object literal semantics only now:

"There are two basic ways to create an object:

var obj = new Object();

And:

var obj = {};

These are semantically equivalent; the second is called object literal syntax, and is more convenient. Object literal syntax was not present in very early versions of the language which is why you see so much code using the old method."

 

dom, javascriptAugust 28, 2006 2:42 pm

The following code finds the row and column numbers of a table cell. The code uses getParent function from the previous post. The obj variable represents a table cell element.

    var oTable =findParent(obj, "table");
    var tr = findParent(obj, "tr");
    var td = findParent(obj, "td");      

    var len= oTable.rows.length;
    while(len–>0){
                if(oTable.rows[len]==tr){
                    var row =len;
                    break;
                }
    }

    var i = tr.cells.length;
    while(i–>0){
                if(tr.cells[i]==td){
                    var col = i;
                    break;
                }
    }
    alert("Row Number :"+ row +"\nColumn number :"+ col);

 

Code, dom, javascriptAugust 25, 2006 5:32 pm

The following function goes up the DOM parent chain until if finds a node whose name was passed as a second parameter.
If it does not find it, it returns null. For example, you can pass it an HTMLTableCellElement as the first argument, and a "TABLE"
 as the second argument, and it will return an HTMLTableElement object.

function findParent(node, parentName){

        while(node.parentNode)
        {
            if(node.parentNode.nodeName==parentName.toUpperCase()){
                return node.parentNode;
            }
            else
                node= node.parentNode;
        }

        return null;
    }

Code, dom, javascriptAugust 23, 2006 6:44 pm

Here is a code sample that converts text in each paragraph to upper case when you place a mouse over it and returns to the original value on mouseout. This may be stupid but it does illustrate a few DOM techniques including how to get a reference to all page elements, and how to create additional properties on an object.  Works only in Firefox at this time.

  function ucListener(){

         //save the existing text in a custom property
        this.firstChild.oldValue = this.firstChild.nodeValue;
        this.firstChild.nodeValue = this.firstChild.nodeValue.toUpperCase();
    }

    function ucListenerOut(){
            this.firstChild.nodeValue = this.firstChild.oldValue;
    }

    function installAllListeners() {
        var elements = document.getElementsByTagName(’*');
        var i = elements.length;
        while(i–>0){
            elements[i].addEventListener(’mouseover’, ucListener, false);
            elements[i].addEventListener(’mouseout’, ucListenerOut, false);
        }
    }

Code, dom 6:04 pm

Here are some handy examples from SlayerOffice that demonstrate how to manipulate and reference DOM Elements: 

1 .Remove a DOM Element  :

    oElement.parentNode.removeChild(oElement);

2. Replace a child element with a new one:

  var newElement = document.createElement("p");
  oldElement.parentNode.replaceChild(newElement, oldElement); 

 3. Remove text from an element:

    var oElement = document.getElementById(obj.id);
    while(oElement.firstChild)
        oElement.removeChild(oElement.firstChild);

 4. Use a DocumentFragment object to speed up loop constructs:

    var oFragment = document.createDocumentFragment();
   var i = 1000;
   while(i–>0) {
     var oElement = document.createElement("div");
     oFragment.appendChild(oElement);
   }
   bodyElement.appendChild(oFragment);

5. Use cloneNode to clear innerHTML:

    var oElement = document.getElementById("myElement");                       
    oElement.parentNode.replaceChild(oElement.cloneNode(false),oElement);

6. Insert an element before the specified element:

    var oldElement = document.getElementById("myElement");
    var newElement =     document.createElement("span");    
   
oldElement.parentNode.insertBefore(newElement , oldElement);

7. Insert an element after the specified element:

    var oldElement = document.getElementById("myElement");
    var
newElement = document.createElement("span");
   
oldElement.parentNode.insertBefore(newElement,oldElement.nextSibling);

8. Get the text value of an element:
     var text = oElement.firstChild.nodeValue;   

9.Get a reference to the next element among the children: 
     var oNode1 = document.getElementById("myDiv").firstChild.nextSibling;

10. Get a reference to the previous element:
   var oNode2 = document.getElementById("myDiv").lastChild.previousSibling;

More techniques:

Insert an element at the top of a page:

var oElement = document.createElement("div"); 
var bodyRef = document.getElementsByTagName("body").item(0);
bodyRef.insertBefore(oElement, document.body.firstChild);

firefoxAugust 22, 2006 4:34 pm

Close Tab         Ctrl+W,  Ctrl+F4   
Close Window    Ctrl+Shift+W,  Alt+F4   
Move Tab Left (when tab is focused) Ctrl+Left Arrow, Ctrl+Up Arrow
Move Tab Right (when tab is focused) Ctrl+Right Arrow, Ctrl+Down Arrow
Move Tab to Beginning (when tab is focused) Ctrl+Home
Move Tab to End (when tab is focused) Ctrl+End
New Tab             Ctrl+T
New Window          Ctrl+N
Next Tab            Ctrl+Tab, Ctrl+Alt+Right Arrow, Ctrl+Page Down
Previous Tab         Ctrl+Shift+Tab, Ctrl+AltOpt+Left Arrow, Ctrl+Page Up
Select Tab (1 to 9) CtrlAltOpt+(1 to 9)

java 12:26 pm

Instance variables in a class are always initialized, even if no constructor exists. The compiler automatically initializes them when it creates an instance. If you have an initial value specified the complier will use that for the initialization. If you don’t have an initial value, it will use defaults as listed below.

  • Numerical values — 0
  • Boolean values — false
  • Object references — null
java 12:24 pm

Here are some navigation shortcuts for Websphere Development Application Studio:

Ctrl+L

Go to line number.

Ctrl+I

Indent the highlighted text.

Ctrl+Q Goto last modified editor position

Ctrl+K

Go to next occurrence of the selected text

Ctrl+Shift+K

Go to previous occurrence of the selected text

Ctrl+F6

Navigate between open Editors (or, files in an editor)

Ctrl+F7

Navigate between open Views

Ctrl+F8

Navigate between open Perspectives

Ctrl+Shift+P Navigating to Matching braces

F12

Jump to the open Editor

Ctrl+Shift+W

List all files open in an editor

Alt+left arrow

Back (last editing position)

Alt+right arrow

Forward (next editing position)

 

 

dom, javascriptAugust 18, 2006 5:38 pm

The algorithm to hide a particular column in a HTML table will be as follows: get a reference to table rows, then cycle through each row, get a reference to a cell belonging to that particular column, and set its style to none: mycell.style.display="none";

More on this and an example is at this page.

javascript 2:07 pm

    Here is an object literal version of a script to calculate JavaScript execution time. It may be useful in development to compare the performance of different scripts. The advantage of the object literal version is that it is compact and should not interfere with existing script function names.

 var timeDiff  =  {
    setStartTime:function (){
        d = new Date();
        time  = d.getTime();
    },

    getDiff:function (){
        d = new Date();
        return (d.getTime()-time);
    }
}

Use it as follows: call timeDiff.setStartTime() at the start of your script and call timeDiff.getDiff() at the end. The timeDiff.getDiff() function will return the script execution time.

Visit  http://franca.exofire.net/jq/ for more JavaScript tips.


Code, javascript 1:58 pm

By default, you can’t use JavaScript to write to the status bar in Firefox. To change the Firefox default behavior in version 1.5, go to “Tools → Options → Content → Enable JavaScript / Advanced"  and check the "Change status bar text” option.

http://blog.taragana.com/index.php/archive/how-to-enable-windowstatus-in-firefox/

 

cssAugust 15, 2006 6:13 pm

If you want to create a table with a spreadsheet-like look, you can use the following style:

 
table, tr, td {

    border-style:solid;
    border-width:1px;
    border-color:#C6C3C6;
    border-collapse:collapse;

}

The important property here is border-collapse which makes table cells share adjacent borders. If you omit it, the default separate value will be used for this property, and the table cells will have their own borders.

Alternatively, one can use the following style with the same effect:

table {
    border-collapse: separate;
}
td {
    border: 1px solid #ccc;
}

 A very nice example on how to build a percentage bar with two images and css!

A very well organized css tutorial at CSS Basics.com.