JDev

javascriptJuly 31, 2006 7:31 pm

    The following script remembers values typed into a text box and populates a pre-defined div section with the cookie values. The values are hyperlinked to the same page.

The usage is simple:

  window.onload = function(){cookies.init("cookieName", "textBoxName", "divId", 180)}; 

The cookies.init function accepts 4 parameters: a cookie name you want to use,  the name of the input box used to enter values,  the id of a div section that will hold cookie values, and  cookie duration in days.

Here is the script:

 
 var cookies = {

    //the default value of the cookie life duration is set at 180 days
     cookieLife : 180,

    //arguments: cookie name
    //   input box name
    //  div id
    // cookie duration in days
     init:function( cookieName, textName, objId, cookieLife){

              this.cookieName = cookieName;
              this.fieldName = textName;

              if(cookieLife){
                  this.cookieLife = cookieLife;
              }

              if(objId){
                  var obj = document.getElementById(objId);
                  if(obj)
                      obj.innerHTML = this.getCookieValues();
                else
                    alert("Can not find object " + objId  );
              }

              var frm = document.getElementsByTagName("form")[0];
            frm.onsubmit = this.addString;
      },

     setCookie: function (value, expires, path, domain, secure) {

         name= this.cookieName;

         document.cookie =
              name + "="
              + escape(value)
              + ((expires) ? "; expires=" + expires.toGMTString() : "")
              + ((path) ? "; path=" + path : "")
              + ((domain) ? "; domain=" + domain : "")
              + ((secure) ? "; secure" : "");
     },

     getCookie: function () {
             var bites = document.cookie.split("; "); // break cookie into array of bites
             for (var i=0; i < bites.length; i++) {
              nextbite = bites[i].split("="); // break into name and value
              if (nextbite[0] == this.cookieName) // if name matches
                return unescape(nextbite[1]); // return value
             }
             return null;
       },

        addString:function (){

            var field = eval ("document.forms[0]."+ cookies.fieldName);

            if(typeof field == "undefined"){
                alert("textName argument is undefined or \ntext input name is not valid");
                return;
            }

            field.value = field.value.replace(/^\s*|\s*$/g,"");
            var txtVal =field.value;

            if(txtVal.length<1)
                return;

            var expires = new Date();
            expires.setDate(expires.getDate() + cookies.cookieLife);

            var contents= cookies.getCookie(cookies.cookieName);

            if(contents != null && contents.length>0){
                var vals = contents.split(".");
                bFound = false;
                for(var i=0; i<vals.length; i++){
                    if(vals[i]==txtVal){
                        bFound = true;
                        break;
                    }
                }
                if(!bFound)
                    contents+="."+txtVal;
            }
            else if(contents == null)
                contents = txtVal;

            cookies.setCookie(contents, expires,"/");
    },

     getCookieValues:function () {

            var val = this.getCookie();
            var html ='’;

            if(val!= null && val.length>0){

                var str = new String(val);
                var aPr = str.split(".");
                var pos=0;
                if((pos = document.location.href.indexOf("?"))>-1)
                    var host = document.location.href.substr(0,pos);
                else
                    var host = document.location.href;

                var vHref = "<a href=’"+ host+"?" + this.fieldName+"=";

                for(var i=0; i<aPr.length; i++){
                    html+= vHref+ aPr[i]+ "’>"+aPr[i]+"</a><br>";
                }
            }
            return html;
        }
    }

 

mysql 5:25 pm

How to limit the number of records retrieved with a select statement: 

    Select * from myTable LIMIT 10

Code, jstlJuly 20, 2006 4:43 pm

The JSTL sql:param tag is real handy to use inside the sql:query tag to supply parameters for sql statements like the following:

    <sql:query var="result">
        SELECT ORDER
        FROM ORDERS
        WHERE CUSTOMER_ID= ?
       <sql:param value=’${param.id}’/>
</sql:query>

However, if you need to use the LIKE condition, the sql:param won’t work. The solution is to use the c:out tag followed by a percentage sign:

  <sql:query var="result">
        SELECT ORDER
        FROM ORDERS
        WHERE YEAR LIKE ‘<c:out value="${param.year}"/>%’
</sql:query>

 

javascriptJuly 18, 2006 8:13 pm

    The near standard cross-browser JavaScript function to add events from Scott Andrew:

function addEvent(obj, evType, fn, useCapture){

  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  }
  else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  }
  else {
         obj[’on’+evType] = fn;
  }
}

dom, javascriptJuly 11, 2006 7:09 pm

The following script can be used instead of an alert to display messages on web pages during development. It creates a div section at the bottom of a page to hold messages. The div section has a button to clear text. The script uses a JavaScript object literal.
 

var messages= {

clear: function (){
    var dcontents = document.getElementById(’cnts’);
    dcontents.innerHTML ='’;
},

debug: function (vText){

    var eldiv = document.getElementById(’msg’);

    if(!eldiv){
        var rdiv = document.createElement("div");

        with(rdiv.style){
            marginLeft= ‘120px’;
            marginRight= ‘400px’;
            borderStyle =’solid’;
            borderWidth= ‘thin’;
            borderColor =’rgb(160, 100, 255)’;
        }
        rdiv.setAttribute("id", "msg");
        //top div
        var dtop = document.createElement("div");
        dtop.style.backgroundColor= ‘#99CC99′;
        dtop.style.borderBottom= ‘1px solid black’;
        dtop.style.textAlign = "right";
        var anchor  = document.createElement("a");
        anchor.href = "javascript:messages.clear()";
        var atext = document.createTextNode("Clear Messages");
        anchor.appendChild(atext);
        dtop.appendChild(anchor);
        rdiv.appendChild(dtop);

        var dcontents = document.createElement("div");
        dcontents.setAttribute("id", "cnts");
        dcontents.style.backgroundColor= ‘#CCCCCC’;
        dcontents.style.paddingLeft= ‘10px’;
        rdiv.appendChild(dcontents);

        var bodyRef = document.getElementsByTagName("body").item(0);
        bodyRef.appendChild(rdiv);

        var txt = document.createTextNode(vText);
        dcontents.appendChild (txt);
    }
    else{
        var dcontents = document.getElementById(’cnts’);
        var br = document.createElement("br");
        dcontents.appendChild(br);
        var sp = document.createElement("span");
        var txt =  document.createTextNode(vText);
        sp.appendChild(txt);
        dcontents.appendChild(sp);
    }
}
}

Usage: messages.debug("some text"); 

You can view the demo page here

 

Code, jstlJuly 4, 2006 7:57 pm

The simplest way to format a date type field in JSTL is to use a formatDate tag. Example:

<fmt:formatDate value="${row[1]}"/>

 This will display a date value in the default format which is MMM-D-YYYY on my Windows XP machine. You can use various attributes such as dateStyle, timeStyle and pattern to customize the date display format.

You can use any of the values default, short, medium, long, or full for the dateStyle attribute.

 This is how you format both date and time using the current date:

 <jsp:useBean id="now" class="java.util.Date" />
 Date : <fmt:formatDate type="both" value="${now}" dateStyle="medium" timeStyle="short"/>
 

A pattern example:

<fmt:formatDate pattern="MMM dd yyyy, HH:mm:ss" value="${row[1]}"/>

In a similar fashion, it’s very easy to format a number as currency in JSTL. Example:

<fmt:formatNumber value="${row[2]}" type="currency"/> 

 One of the best books on JSTL is written by Shawn Bayern, the reference implementation lead for JSTL.
 

jstl 7:18 pm

    With JSTL it is easy to display query results on a web page. Most online tutorials list code similar to the following:

<sql:query var="queryResults" dataSource="${dataSrc}">
    select * from employees
</sql:query>
 

<c:forEach var="row" items="${queryResults.rows}">

     <c:out value="${row.id}"/>
    <c:out value="${row.lastname"/>

</c:forEach>
 

What if you want to display table values referring to the multiple array which is the result set by column index instead of column name. You should use the following syntax:

  <c:out value="${row [0]}"/>
  <c:out value="${row [1]}"/>

However, it is not enough. When you use the forEach tag, you should also use rowsByIndex property of the Result object as follows: 

<c:forEach var="row" items="${queryResults.rowsByIndex}">   

Only then your jsp will be valid and will not throw an exception.