Javascript Time functions

The Date object has been created and now we have a variable that holds the current date. To get the information we need to print out the date we have to utilize some or all of the following functions:

  • getTime() – Number of milliseconds since 1/1/1970 @ 12:00 AM
  • getSeconds() – Number of seconds (0-59)
  • getMinutes() – Number of minutes (0-59)
  • getHours() – Number of hours (0-23)
  • getDay() – Day of the week(0-6). 0 = Sunday, … , 6 = Saturday
  • getDate() – Day of the month (0-31)
  • getMonth() – Number of month (0-11)
  • getFullYear() – The four digit year (1970-9999)

Today’s Date

<!– hide from old browsers
document.write(getDateStr())
//–>
June 19, 2008

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  function GetMonth(intMonth){
    var MonthArray = new Array("January", "February", "March",
                               "April", "May", "June",
                               "July", "August", "September",
                               "October", "November", "December")
    return MonthArray[intMonth]
    }
  function getDateStr(){
    var today = new Date()
    var year = today.getYear()
    if(year<1000) year+=1900
    var todayStr = GetMonth(today.getMonth()) + " " + today.getDate()
    todayStr += ", " + year
    return todayStr
    }
//–>
</SCRIPT>

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
    document.write(getDateStr())
//-->
</SCRIPT>

Today’s Date including day of week

<!– hide from old browsers
document.

write(getDateStrWithDOW())
//–>
Thursday, June 19, 2008

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  function GetDay(intDay){
    var DayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
                         "Thursday", "Friday", "Saturday")
    return DayArray[intDay]
    }
 
  function GetMonth(intMonth){
    var MonthArray = new Array("January", "February", "March",
                               "April", "May", "June",
                               "July", "August", "September",
                               "October", "November", "December")
    return MonthArray[intMonth]
    }
  function getDateStrWithDOW(){
    var today = new Date()
    var year = today.getYear()
    if(year<1000) year+=1900
    var todayStr = GetDay(today.getDay()) + ", "
    todayStr += GetMonth(today.getMonth()) + " " + today.getDate()
    todayStr += ", " + year
    return todayStr
    }
//–>
</SCRIPT>

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
    document.write(getDateStrWithDOW())
//-->
</SCRIPT>

Todays Date (short format)

<!– hide from old browsers
var today = new Date()
var year = today.getYear()
if(year<1000) year+=1900

document.write((today.getMonth()+1) + “/” +
today.getDate() + “/” + (year+””).substring(2,4))
//–>
6/19/08

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var today = new Date()
  var year = today.getYear()
  if(year<1000) year+=1900
 
  document.write((today.getMonth()+1) + "/" +
                  today.getDate() + "/" + (year+"").substring(2,4))
//-->
</SCRIPT>

Todays Date (short format, full year)

<!– hide from old browsers
var today = new Date()
var year = today.getYear()
if(year<1000) year+=1900

document.write((today.getMonth()+1) + “/” +
today.getDate() + “/” + year)
//–>
6/19/2008

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var today = new Date()
  var year = today.getYear()
  if(year<1000) year+=1900
 
  document.write((today.getMonth()+1) + "/" +
                  today.getDate() + "/" + year)
//-->
</SCRIPT>

Todays Date (short format, leading zeros)

<!– hide from old browsers
var today = new Date()
var month = today.getMonth()+1
var year = today.getYear()
var day = today.getDate()
if(day<10) day = “0″ + day
if(month<10) month= “0″ + month
if(year<1000) year+=1900

document.write(month + “/” + day +
“/” + (year+””).substring(2,4))
//–>
06/19/08

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var today = new Date()
  var month = today.getMonth()+1
  var year = today.getYear()
  var day = today.getDate()
  if(day<10) day = "0" + day
  if(month<10) month= "0" + month
  if(year<1000) year+=1900
 
  document.write(month + "/" + day +
                 "/" + (year+"").substring(2,4))
//-->
</SCRIPT>

Todays Date (short format, leading zeros, full year)

<!– hide from old browsers
var today = new Date()
var month = today.getMonth()+1
var year = today.getYear()
var day = today.getDate()
if(day<10) day = “0″ + day
if(month<10) month= “0″ + month
if(year<1000) year+=1900

document.write(month + “/” + day +
“/” + year)
//–>
06/19/2008

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var today = new Date()
  var month = today.getMonth()+1
  var year = today.getYear()
  var day = today.getDate()
  if(day<10) day = "0" + day
  if(month<10) month= "0" + month
  if(year<1000) year+=1900
 
  document.write(month + "/" + day +
                 "/" + year)
//-->
</SCRIPT>

Todays Date (European format)

<!– hide from old browsers
var today = new Date()
var year = today.getYear()
if(year<1000) year+=1900

document.write(today.getDate() + “.” +
(today.getMonth()+1) + “.” + (year+””).substring(2,4))
//–>
19.6.08

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var today = new Date()
  var year = today.getYear()
  if(year<1000) year+=1900
 
  document.write(today.getDate() + "." +
                 (today.getMonth()+1) + "." + (year+"").substring(2,4))
//-->
</SCRIPT>

Basic Date and Time

<!– hide from old browsers
var curDateTime = new Date()
document.write(curDateTime)
//–>
Thu Jun 19 2008 12:02:04 GMT+0530 (India Standard Time)

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  document.write(curDateTime)
//-->
</SCRIPT>

Date and Time (24-hr format)

<!– hide from old browsers
var curDateTime = new Date()
document.write(curDateTime.toLocaleString())
//–>
Thursday, 19 June, 2008 12:02

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  document.write(curDateTime.toLocaleString())
//-->
</SCRIPT>

Basic GMT Date and Time

<!– hide from old browsers
var curDateTime = new Date()
document.write(curDateTime.toGMTString())
//–>
Thu, 19 Jun 2008 06:32:04 GMT

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  document.write(curDateTime.toGMTString())
//-->
</SCRIPT>

Time in 12-hr format

<!– hide from old browsers
var curDateTime = new Date()
var curHour = curDateTime.getHours()
var curMin = curDateTime.getMinutes()
var curSec = curDateTime.getSeconds()
var curAMPM = ” AM”
var curTime = “”
if (curHour >= 12){
curHour -= 12
curAMPM = ” PM”
}
if (curHour == 0) curHour = 12
curTime = curHour + “:”
+ ((curMin < 10) ? “0″ : “”) + curMin + “:”
+ ((curSec < 10) ? “0″ : “”) + curSec
+ curAMPM
document.write(curTime)
//–>
12:02:04 PM

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  var curHour = curDateTime.getHours()
  var curMin = curDateTime.getMinutes()
  var curSec = curDateTime.getSeconds()
  var curAMPM = " AM"
  var curTim


e = ""
  if (curHour >= 12){
    curHour -= 12
    curAMPM = " PM"
    }
  if (curHour == 0) curHour = 12
  curTime = curHour + ":"
    + ((curMin < 10) ? "0" : "") + curMin + ":"
    + ((curSec < 10) ? "0" : "") + curSec
    + curAMPM
  document.write(curTime)
//-->
</SCRIPT>

Time in 24-hr format

<!– hide from old browsers
var curDateTime = new Date()
var curHour = curDateTime.getHours()
var curMin = curDateTime.getMinutes()
var curSec = curDateTime.getSeconds()
var curTime =
((curHour < 10) ? “0″ : “”) + curHour + “:”
+ ((curMin < 10) ? “0″ : “”) + curMin + “:”
+ ((curSec < 10) ? “0″ : “”) + curSec
document.write(curTime)
//–>
12:02:04

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  var curHour = curDateTime.getHours()
  var curMin = curDateTime.getMinutes()
  var curSec = curDateTime.getSeconds()
  var curTime =
    ((curHour < 10) ? "0" : "") + curHour + ":"
    + ((curMin < 10) ? "0" : "") + curMin + ":"
    + ((curSec < 10) ? "0" : "") + curSec
  document.write(curTime)
//-->
</SCRIPT>

Time for Specific Time Zone

<!– hide from old browsers
// Copyright 1999, 2000 by Ray Stott
// OK to use if this copyright is included
// Script available at http://www.crays.com/jsc
var TimezoneOffset = -8 // adjust for time zone
var localTime = new Date()
var ms = localTime.getTime()
+ (localTime.getTimezoneOffset() * 60000)
+ TimezoneOffset * 3600000
var time = new Date(ms)
var hour = time.getHours()
var minute = time.getMinutes()
var second = time.getSeconds()
var curTime = “” + ((hour > 12) ? hour – 12 : hour)
if(hour==0) curTime = “12″
curTime += ((minute < 10) ? “:0″ : “:”) + minute
curTime += ((second < 10) ? “:0″ : “:”) + second
curTime += (hour >= 12) ? ” PM” : ” AM”
document.write(curTime + ” – US Pacific Time”)
//–>
10:32:04 PM – US Pacific Time

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  // Copyright 1999, 2000 by Ray Stott
  // OK to use if this copyright is included
  // Script available at http://www.crays.com/jsc
  var TimezoneOffset = -8  // adjust for time zone
  var localTime = new Date()
  var ms = localTime.getTime()
             + (localTime.getTimezoneOffset() * 60000)
             + TimezoneOffset * 3600000
  var time =  new Date(ms)
  var hour = time.getHours()
  var minute = time.getMinutes()
  var second = time.getSeconds()
  var curTime = "" + ((hour > 12) ? hour - 12 : hour)
  if(hour==0) curTime = "12"
  curTime += ((minute < 10) ? ":0" : ":") + minute
  curTime += ((second < 10) ? ":0" : ":") + second
  curTime += (hour >= 12) ? " PM" : " AM"
  document.write(curTime + " US Pacific Time")
//-->
</SCRIPT>

GMT Time

<!– hide from old browsers
var curDateTime = new Date()
var curHour = curDateTime.getHours()
+ curDateTime.getTimezoneOffset()/60
if (curHour > 24) curHour -= 24
if (curHour < 0) curHour += 24
var curMin = curDateTime.getMinutes()
var curSec = curDateTime.getSeconds()
var curTime =
((curHour < 10) ? “0″ : “”) + curHour + “:”
+ ((curMin < 10) ? “0″ : “”) + curMin + “:”
+ ((curSec < 10) ? “0″ : “”) + curSec
document.write(curTime + ” GMT”)
//–>
06.5:02:04 GMT

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  var curHour = curDateTime.getHours()
     + curDateTime.getTimezoneOffset()/60
  if (curHour > 24)  curHour -= 24
  if (curHour < 0) curHour += 24
  var curMin = curDateTime.getMinutes()
  var curSec = curDateTime.getSeconds()
  var curTime =
    ((curHour < 10) ? "0" : "") + curHour + ":"
    + ((curMin < 10) ? "0" : "") + curMin + ":"
    + ((curSec < 10) ? "0" : "") + curSec
  document.write(curTime + " GMT")
//-->
</SCRIPT>

Offset from GMT

<!– hide from old browsers
var curDateTime = new Date()
document.write(“GMT Offset for your time zone is “)
document.write(-(curDateTime.getTimezoneOffset()/60))
//–>
GMT Offset for your time zone is 5.5

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
  var curDateTime = new Date()
  document.write("GMT Offset for your time zone is ")
  document.write(-(curDateTime.getTimezoneOffset()/60))
//-->
</SCRIPT>

Days till Y3K

<!– hide from old browsers
var today = new Date()
var targetDate = new Date(“01/01/3000″) //use full year
var timeBeforeTarget = Math.floor(( targetDate.getTime()
– today.getTime()) / 86400000)
var msg = “<B>There are only ” + (timeBeforeTarget +1)
+ ” days until the year 3000.</B>”
document.write(msg)
//–>
There are only 362151 days until the year 3000.

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
var today = new Date()
var targetDate = new Date("01/01/3000") //use full year
var timeBeforeTarget = Math.floor(( targetDate.getTime()
        - today.getTime()) / 86400000)
var msg = "<B>There are only "  + (timeBeforeTarget +1)
         + " days until the year 3000.</B>"
document.write(msg)
//-->
</SCRIPT>

Days after a Certain Date

<!– hide from old browsers
var today = new Date()
var targetDate = new Date(“12/31/1999″) //use full year
var timeAfterTarget = Math.floor(( today.getTime()
– targetDate.getTime() ) / 86400000)
var msg = “This is day number ” + timeAfterTarget + ” for this year.”
document.write(msg)
//–>
This is day number 3093 for this year.

 
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
var today = new Date()
var targetDate = new Date("12/31/1999") //use full year
var timeAfterTarget = Math.floor(( today.getTime()
        - targetDate.getTime() ) / 86400000)
var msg = "This is day number " + timeAfterTarget + " for this year."


document.write(msg)
//-->
</SCRIPT>

Additional Information on These Scripts

All scripts are Y2K compliant.

The Basic Date and Time, Date and Time (24-hr format) and Basic GMT Date and Time are easy to implement but the results displayed will be different for different browsers and operating systems. All of the other scripts should display the same results for all browsers and operating systems.

The Time for a Specific Time Zone script can be set for any time zone by changing the TimeZoneOffset variable. If you don’t know your time zone offset, you can find it out by using the Offset from GMT script. You may need to change this value twice a year to adjust for Daylight Savings Time.

Days till Y3K script can be used for other important dates by changing the date that is used to initialize the targetDate variable. Likewise, The Days after a Certain Date script can be used to count the days after a different date by changing the date that is used to initialize the targetDate variable. It is also important that you specify these dates with the full year, ie 2000 rather than 00, to be Y2K compliant.

configure CVS connection

How do I configure CVS connection settings?

  • You can specify connection settings in the Checkout wizard. Settings are persistently stored.

For example, to check out NetBeans sources, choose Versioning > Checkout (or Versioning > CVS > Checkout) from the main menu and use :pserver:anoncvs@cvs.netbeans.org:/cvs with empty password for anonymous checkout. Alternatively use your own NetBeans.org login and password instead of anoncvs.

  • Otherwise, the IDE uses automatic configuration detection (probing common cvs setup files). Open the Favorites window, and right-click to add and open an existing repository directory. If the cvs session fails, the IDE shows the connection configuration dialog so you can change the settings (e.g. configure a proxy).

Applies to: NetBeans 6.x, 5.x

Expression Language

Expression Language

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property.

The test attribute of the following conditional tag is supplied with an EL expression that compares the number of items in the session-scoped bean named cart with 0:

<c:if test="${sessionScope.cart.numberOfItems > 0}"> 
  ...
</c:if> 

The JSP expression evaluator is responsible for handling EL expressions, which are enclosed by the ${ } characters and can include literals. Here’s an example:

<c:if test="${bean1.a < 3}" >
  ...
</c:if> 

Any value that does not begin with ${ is treated as a literal and is parsed to the expected type using the PropertyEditor for the type:

<c:if test="true" >
...
</c:if> 

Literal values that contain the ${ characters must be escaped as follows:

<mytags:example attr1="an expression is ${'${'}true}" /> 

Deactivating Expression Evaluation

Because the pattern that identifies EL expressions–${ }–was not reserved in the JSP specifications before JSP 2.0, there may be applications where such a pattern is intended to pass through verbatim. To prevent the pattern from being evaluated, you can deactivate EL evaluation.

To deactivate the evaluation of EL expressions, you specify the isELIgnored attribute of the page directive:

<%@ page isELIgnored ="true|false" %> 

The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

The default value varies depending on the version of the web application deployment descriptor. The default mode for JSP pages delivered using a Servlet 2.3 or earlier descriptor is to ignore EL expressions; this provides backward compatibility. The default mode for JSP pages delivered with a Servlet 2.4 descriptor is to evaluate EL expressions; this automatically provides the default that most applications want. You can also deactivate EL expression evaluation for a group of JSP pages (see Deactivating EL Expression Evaluation).

Using Expressions

EL expressions can be used:

  • In static text
  • In any standard or custom tag attribute that can accept an expression

The value of an expression in static text is computed and inserted into the current output. If the static text appears in a tag body, note that an expression will not be evaluated if the body is declared to be tagdependent (see body-content Attribute).

There are three ways to set a tag attribute value:

  • With a single expression construct:

<some:tag value="${expr}"/>

The expression is evaluated and the result is coerced to the attribute’s expected type.

  • With one or more expressions separated or surrounded by text:

<some:tag value="some${expr}${expr}text${expr}"/>

The expressions are evaluated from left to right. Each expression is coerced to a String and then concatenated with any intervening text. The resulting String is then coerced to the attribute’s expected type.

  • With text only:

<some:tag value="sometext"/>

In this case, the attribute’s String value is coerced to the attribute’s expected type.

Expressions used to set attribute values are evaluated in the context of an expected type. If the result of the expression evaluation does not match the expected type exactly, a type conversion will be performed. For example, the expression ${1.2E4} provided as the value of an attribute of type float will result in the following conversion:

Float.valueOf("1.2E4").floatValue()  

See section JSP2.8 of the JSP 2.0 specification for the complete type conversion rules.

Variables

The web container evaluates a variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String). For example, when evaluating the expression ${product}, the container will look for product in the page, request, session, and application scopes and will return its value. If product is not found, null is returned. A variable that matches one of the implicit objects described in Implicit Objects will return that implicit object instead of the variable’s value.

Properties of variables are accessed using the . operator and can be nested arbitrarily.

The JSP expression language unifies the treatment of the . and [] operators. expr-a.identifier-b is equivalent to expr-a["identifier-b"]; that is, the expression expr-b is used to construct a literal whose value is the identifier, and then the [] operator is used with that value.

To evaluate expr-a[expr-b], evaluate expr-a into value-a and evaluate expr-b into value-b. If either value-a or value-b is null, return null.

  • If value-a is a Map, return value-a.get(value-b). If !value-a.containsKey(value-b), then return null.
  • If value-a is a List or array, coerce value-b to int and re

    turn value-a.get(value-b) or Array.get(value-a, value-b), as appropriate. If the coercion couldn’t be performed, an error is returned. If the get call returns an IndexOutOfBoundsException, null is returned. If the get call returns another exception, an error is returned.

  • If value-a is a JavaBeans object, coerce value-b to String. If value-b is a readable property of value-a, then return the result of a get call. If the get method throws an exception, an error is returned.

Implicit Objects

The JSP expression language defines a set of implicit objects:

In addition, several implicit objects are available that allow easy access to the following objects:

  • param: Maps a request parameter name to a single value
  • paramValues: Maps a request parameter name to an array of values
  • header: Maps a request header name to a single value
  • headerValues: Maps a request header name to an array of values
  • cookie: Maps a cookie name to a single cookie
  • initParam: Maps a context initialization parameter name to a single value

Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.

  • pageScope: Maps page-scoped variable names to their values
  • requestScope: Maps request-scoped variable names to their values
  • sessionScope: Maps session-scoped variable names to their values
  • applicationScope: Maps application-scoped variable names to their values

When an expression references one of these objects by name, the appropriate object is returned instead of the corresponding attribute. For example, ${pageContext} returns the PageContext object, even if there is an existing pageContext attribute containing some other value.

Literals

The JSP expression language defines the following literals:

  • Boolean: true and false
  • Integer: as in Java
  • Floating point: as in Java
  • String: with single and double quotes; " is escaped as ", ‘ is escaped as ‘, and is escaped as \.
  • Null: null

Operators

In addition to the . and [] operators discussed in Variables, the JSP expression language provides the following operators:

  • Arithmetic: +, - (binary), *, / and div, % and mod, - (unary)
  • Logical: and, &&, or, ||, not, !
  • Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le. Comparisons can be made against other values, or against boolean, string, integer, or floating point literals.
  • Empty: The empty operator is a prefix operation that can be used to determine whether a value is null or empty.
  • Conditional: A ? B : C. Evaluate B or C, depending on the result of the evaluation of A.

The precedence of operators highest to lowest, left to right is as follows:

  • [] .
  • () – Used to change the precedence of operators.
  • - (unary) not ! empty
  • * / div % mod
  • + - (binary)
  • < > <= >= lt gt le ge
  • == != eq ne
  • && and
  • || or
  • ? :

Reserved Words

The following words are reserved for the JSP expression language and should not be used as identifiers.

and   eq   gt   true   instanceof
or    ne   le   false  empty
not   lt   ge   null   div   mod 

Note that many of these words are not in the language now, but they may be in the future, so you should avoid using them.

Examples

Table 12-2 contains example EL expressions and the result of evaluating them.

Table 12-2 Example Expressions 

EL Expression

Result

${1 > (4/2)}

false

${4.0 >= 3}

true

${100.0 == 100}

true

${(10*10) ne 100}

false

${a < b}

true

${hip gt hit}

false

${4 > 3}

true

${1.2E4 + 1.4}

12001.4

${3 div 4}

0.75

${10 mod 4}

2

${empty param.Add}

True if the request parameter named Add is null or an empty string

${pageContext.request.contextPath}

The context path

${sessionScope.cart.numberOfItems}

The value of the numberOfItems property of the session-scoped attribute named cart

${param[mycom.productId]}

The value of the request parameter named mycom.productId

${header["host"]}

The host

${departments[deptName]}

The value of the entry named deptName in the departments map

${requestScope['javax.servlet.
forward.servlet_path']}

The value of the request-scoped attribute named javax.servlet.
forward.servlet_path

Functions

The JSP expression language allows you to define a function that can be invoked in an expression. Functions are defined using the same mechanisms as custom tags (See Using Custom Tags and Chapter 15).

Using Functions

Functions can appear in static text and tag attribute values.

To use a function in a JSP page, you use a taglib directive to import the tag library containing the function. Then you preface the function invocation with the prefix declared in the directive.

For example, the date example page index.jsp imports the /functions library and invokes the function equals in an expression:

<%@ taglib prefix="f" uri="/functions"%>
...
    <c:when
      test="${f:equals(selectedLocaleString,
        localeString)}" > 

Defining Functions

To define a function you program it as a public static method in a public class. The mypkg.MyLocales class in the date example defines a function that tests the equality of two Strings as follows:

package mypkg;
public class MyLocales {
 
  ...
  public static boolean equals( String l1, String l2 ) {
    return l1.equals(l2);
  }
} 

Then you map the function name as used in the EL expression to the defining class and function signature in a TLD. The following functions.tld file in the date example maps the equals function to the class containing the implementation of the function equals and the signature of the function:

<function>
  <name>equals</name>
<


span style='font-size:10pt;'>  <function-class>mypkg.MyLocales</function-class>
  <function-signature>boolean equals( java.lang.String,
    java.lang.String )</function-signature>
</function> 

A tag library can have only one function element that has any given name element.

 

JSTL Examples

JSTL Examples
Select font size:
8pt 9pt 10pt 11pt 12pt 14pt 16pt
Download the

JSTLexamples.war
archive. This archive contains the following files:

index.jsp Script with a variety of examples
bean/MyBean.java User-defined bean example
mytaglib/MyFunctions.java JSTL tag library classes
Functions.tld JSTL tag library definition
Install and run in Eclipse
Prior to starting eclipse, you need to make available two new library JAR files which are included in the apache-tomcat distribution but not available for all applications. Locate the directory:

apache-tomcat-6.0.14/webapps/jsp-examples/WEB-INF/lib/

and within it, the files:

jstl.jar standard.jar

Simply copy these two files into:

apache-tomcat-6.0.14/common/lib/

Then start up eclipse. Follow the steps in JSP Forms import the WAR file JSTLexamples.war and run the project on Tomcat.

The JSP Standard Tag Library (JSTL)
The JSTL library provides a means, through variables, expressions and tags, to avoid the interleaving of Java and tag-style code. Using this language, we can, for the most part, eliminate explicit Java code in JSP pages in favor of augmenting the XML-like tag structure. See

http://jakarta.apache.org/taglibs/
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/
You should refer to this online documentation:

jstl tld docs
and/or download it yourself:

jstl-1_1-mr2-spec-tlddoc.zip
The standard tags are those described in the table below. We have omitted the sql tags since we don’t plan to use SQL done directly in JSP. Using one of tag groups is effected by the addition of one of the following respective tag statements below.

c: <%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
fn: <%@taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions” %>
fmt: <%@taglib prefix=”fmt” uri=”http://java.sun.com/jsp/jstl/fmt” %>
xml: <%@taglib prefix=”x” uri=”http://java.sun.com/jsp/jstl/xml” %>

The uri is simply an identifier of the tag set. The prefix is determinable by the user, but the prefixes seen here are standard.

TLD tags and functions c: core fmt: formatting fn: functions x: xml
c:catch
c:choose
c:forEach
c:forTokens
c:if
c:import
c:otherwise
c:out
c:param
c:redirect
c:remove
c:set
c:url
c:when
fmt:bundle
fmt:formatDate
fmt:formatNumber
fmt:message
fmt:param
fmt:parseDate
fmt:parseNumber
fmt:requestEncoding
fmt:setBundle
fmt:setLocale
fmt:setTimeZone
fmt:timeZone
fn:contains()
fn:containsIgnoreCase()
fn:endsWith()
fn:escapeXml()
fn:indexOf()
fn:join()
fn:length()
fn:replace()
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()

x:choose
x:forEach
x:if
x:otherwise
x:out
x:param
x:parse
x:set
x:transform
x:when

These and other tag systems are used in JSP in one of two forms:

<tag-prefix:type attribute1=”VALUE1″ …

or, as functions to create expressions:

tag-prefix:function(arg1,arg2,…)

As in XML, tags can be complete, using a single tag ending with “/>“, or in pairs, containing a content terminated by a matching ending tag </tag-prefix:tag-type>. Some example of the common usages of the “c” tags are these:

<c:out value=”…” escapeXml=”true”/>
<c:set var=”x” value=”…” />
<c:if test=”…” > … </c:if>
<c:forEach var=”x” items=”…” > … </c:forEach>

Expression Language (EL)
The syntax for what replaces the “…” above is specified by a Java-like language, unimaginately called Expression Language (EL). EL is part of JSP; its expressions are all surrounded by the syntax ${ }. but typically can only be used most effectively in conjunction with JSTL tags. EL is closely related to Java but has some extensions and conceptual simplifications. In particular, EL is more like other web script languages being loosely typed along with other semantic simplifications. EL expressions permit variables and most of the usual arithmetic and boolean operators. Here are some points:

The == operator for strings functions like the Java .equals operator.
an EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string.
EL has a unary operator empty: empty(x) acts like the expression x==null but also means “x equals the empty string”.
the operators or, and are synonyms for ||, &&, respectively.
Query parameters
The value of the parameter “xx” is expressed by the EL expression param.xx. When used directly in HTML,

${param.xx}

is equivalent to the JSP expression:

<%= (request.getParameter(“xx”) != null) ? (request.getParameter(“xx”) : “” %>

Session variables are EL variables
A session variable x automatically becomes available as an EL variable, e.g. if we have:

<%
session.setAttribute( “x”, “hello” );
// or
pageContext.setAttribute( “x”, “hello” );
%>

x = ${x} <!– prints: x = hello — >

JSP beans in JSTL
The EL language provides a simplified syntax for accessing bean’s get/set accessor functions. For example, the bean we use in the examples below is this:

<jsp:useBean id=”mb” class=”bean.MyBean” />

from the class:

——————————————————————————– bean/MyBean.java

package bean;

public class MyBean {
private String count;
public String getCount() { return count; }
public void setCount(String count) { this.count = count; }
public MyBean() {
System.out.println(”MyBean intialized”);
count = “0?;
}
}
EL treats the expression ${mb.count} as the value of mb.getCount(). A typical JSTL tag statement is something like

<c:set var=”i” value=”${mb.count}” />

The c:set tag is also used to call the set member function as follows:

<c:set target=”${mb}” property=”count” value=”5″ />

is equivalent to mb.setCount(”5?). Caution: If you use both set and get property, they must be consistent. For example, suppose you have these member functions:

String getSomeProperty() { … }
void setSomeProperty(int n) { … }

Then EL will consider this a mismatch and most likely reject the setter member function if you tried to use:

<c:set target=”${mb}” property=”someProperty” value=”5″ />

We can also remove a bean from the session using the JSTL c:remove tag:

<c:remove var=”mb” />

Data structures: arrays, arrays, maps, sets
Arrays and maps permit access to their collection via indices: arrays via integer indices and maps via key indices. EL regards both of these accesses as syntactically similar using the [ ] operator. For example:

<%
Map<String,String> theMap = new HashMap<String,String>();
theMap.put(“John”, “5”); theMap.put(“Jim”, “7”);
String theArray[] = { “aaa”, “bbb”, “ccc” };

session.setAttribute( “theMap”, theMap );
session.setAttribute( “theArray”, theArray );
%>

${theMap[“Jim”]} <!– same as theMap.get(”Jim”), outputs 7 –>
${theArray[1]} <!– outputs bbb –>

The EL expressions for maps, sets and lists can all print directly. Arrays,
as in Java, don’t print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose:

${fn:join(theArray,”,”)}

Iterating over data structures
In order to iterate over an array, list, map, or set, the c:forEach tag pair serves our interests. Iteration with c:forEach treats arrays, lists and sets identically. For example, this code will iteratively print the elements:

<!– L represents either an array, list or set –>
<c:forEach var=”x” items=”${L}” >
${x}
</c:forEach>

When using a map, the iteration generates Map.Entry pairs. Using the getKey and getValue functions the structure of the JSTL code to iteratively print the key/value pairs looks like this:

<!– M is a map –>
<c:forEach var=”x” items=”${M}” >
${x.key}: ${x.value}
</c:forEach>

Choice tags c:if, c:choose/c:when
The c:if tag generates a choice situation with a syntax like:

<c:if test=”${EL_BOOLEAN_EXPRESSION}” > … </c:if>

The EL_BOOLEAN_EXPRESSION uses the usual boolean operators with simplifications and additions as mentioned above. If-else structures are based on the c:choose/c:when/c:otherwise tags:

<c:choose>
<c:when test=”${EL_EXPR1}”> … </c:when>
<c:when test=”${EL_EXPR2}”> … </c:when>

<c:otherwise> … </c:otherwise>
</c:choose>

User-generated tag functions
If one wants to avoid explicit JSP sections of code then the Java classes and functions must be able to be accessed through the tag system. Beans provide a limited way of doing so through combinations of “get/set” member functions, but this is not intended for utility functions to manipulate objects. The fn tags provide some of these utility functions, but one can imagine that soon there would be need for your own specific utility functions. Towards this end, JSP provides a means to add your own tag libraries using a combination of Java classes and Tag Library Definition (TLD) files. Both XML-like tags and EL function tags can be added, but it’s much easier to create user-defined EL function tags. The utility functions used must be static functions. For example, suppose we want to use the function defined in this class in an EL expression.

——————————————————————————– mytaglib/MyFunctions.java

package mytaglib;
import java.util.*;
public class MyFunctions {
public static boolean contains(Set<String> set, String target) {
return set.contains(target);
}
}
The glue which connects this functions to JSP is the XML file MyTags.tld held stored in the /WEB-INF/ project directory.

——————————————————————————– MyTags.tld

<?xml version=”1.0? encoding=”UTF-8??>
<taglib version=”2.0? …>
<tlib-version>1.1</tlib-version>
<uri>/WEB-INF/MyTags</uri>
<function>
<name>contains</name>
<function-class>mytaglib.MyFunctions</function-class>
<function-signature>
boolean contains(java.util.Set,java.lang.String)
</function-signature>
</function>
</taglib>
This file defines a uri by which it is accessed and a set of function prototypes in XML format. Each function has a tag name, the class it belongs to and the actual function prototype within this class. The necessary specification within the JSP file is something like this:

<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

The prefix chosen specifies how the function will be referenced within the EL syntax — it can be anything you want, so long as it doesn’t conflict with another tag set. In this case the function will be prefaced by mtg: as in this example:

<c:if test=”${mtg:contains(someSet,someValue)}” > … </c:if>

Example script
——————————————————————————– index.jsp

<%@ page language=”java” contentType=”text/html;
charset=US-ASCII” pageEncoding=”US-ASCII”%>

<%@page import=”java.util.*”%>

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
<%@taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions”%>
<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

<jsp:useBean id=”mb” scope=”session” class=”bean.MyBean” />

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>
<title>Insert title here</title>
<style>
h4 { color: red; margin-bottom:0px; text-decoration: underline; }
</style>
</head>
<body>
<%
String x = “testing”;
String[] a = { “xx”, “yy”, “zz” };

Map<String, String> m = new LinkedHashMap<String, String>();
m.put(”aa”, “1?);
m.put(”bb”, “2?);
m.put(”cc”, “3?);

List<String> l = new ArrayList<String>();
l.add(”nn”);
l.add(”mm”);
l.add(”oo”);
Set<String> s = new LinkedHashSet<String>();
s.add(”aa”);
s.add(”bb”);
s.add(”cc”);
session.setAttribute(”x”, x);
session.setAttribute(”a”, a);
session.setAttribute(”m”, m);
session.setAttribute(”l”, l);
session.setAttribute(”s”, s);
%>
<h4>access values of query parameter p</h4>
<c:if test=”${param.p == null}”>param.p not defined<br /></c:if>
first value: ${param.p}<br />
all values: ${fn:join(paramValues.p,”,”)}

<h4>print objects</h4>
x: ${x}<br />
m: ${m}<br />
s: ${s}<br />
l: ${l}<br />

<h4>print array using join</h4>
a: ${fn:join(a,”,”)}
<br />

<h4>access individuals of array or map via [ ]</h4>
a[1]: ${a[1]}
<br />
m[“bb”]: ${m[“bb”]}
<br />

<h4>access individuals in c:forEach loop</h4>
a: <c:forEach var=”i” items=”${a}”>${i} </c:forEach><br />
s: <c:forEach var=”i” items=”${s}”>${i} </c:forEach><br />
l: <c:forEach var=”i” items=”${l}”>${i} </c:forEach><br />
m: <c:forEach var=”i” items=”${m}”>${i.key}=>${i.value} </c:forEach><br />

<h4>using c:set and escapeXml</h4>
<c:set var=”k” value=”<b>bold</b>” />
k: ${k}<br />
escaped(k): ${fn:escapeXml(k)}<br />
c:out escaped: <c:out value=”${k}” escapeXml=”true” />

<h4>using a bean’s get and set properties indirectly</h4>
mb.count: ${mb.count}:
<c:set target=”${mb}” property=”count” value=”${mb.count + 1}” />
<c:choose>
<c:when test=”${mb.count > 6}”>
became bigger than 6, re-initialize mb
<c:remove var=”mb” />
</c:when>
<c:when test=”${mb.count > 3}”>became bigger than 3</c:when>
<c:otherwise>no more than 3</c:otherwise>
</c:choose>

<h4>User defined tag functions</h4>
s: ${s}<br />
<c:set var=”t” value=”cc” />
s.contains(${t}): ${mtg:contains(s,t)}<br />
<c:set var=”t” value=”dd” />
s.contains(${t}): ${mtg:contains(s,t)}

</body>
</html>
Regards
R.Satish Kumar
JSTL Examples
Select font size:
8pt 9pt 10pt 11pt 12pt 14pt 16pt
Download the

JSTLexamples.war
archive. This archive contains the following files:

index.jsp Script with a variety of examples
bean/MyBean.java User-defined bean example
mytaglib/MyFunctions.java JSTL tag library classes
Functions.tld JSTL tag library definition
Install and run in Eclipse
Prior to starting eclipse, you need to make available two new library JAR files which are included in the apache-tomcat distribution but not available for all applications. Locate the directory:

apache-tomcat-6.0.14/webapps/jsp-examples/WEB-INF/lib/

and within it, the files:

jstl.jar standard.jar

Simply copy these two files into:

apache-tomcat-6.0.14/common/lib/

Then start up eclipse. Follow the steps in JSP Forms import the WAR file JSTLexamples.war and run the project on Tomcat.

The JSP Standard Tag Library (JSTL)
The JSTL library provides a means, through variables, expressions and tags, to avoid the interleaving of Java and tag-style code. Using this language, we can, for the most part, eliminate explicit Java code in JSP pages in favor of augmenting the XML-like tag structure. See

http://jakarta.apache.org/taglibs/
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/
You should refer to this online documentation:

jstl tld docs
and/or download it yourself:

jstl-1_1-mr2-spec-tlddoc.zip
The standard tags are those described in the table below. We have omitted the sql tags since we don’t plan to use SQL done directly in JSP. Using one of tag groups is effected by the addition of one of the following respective tag statements below.

c: <%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
fn: <%@taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions” %>
fmt: <%@taglib prefix=”fmt” uri=”http://java.sun.com/jsp/jstl/fmt” %>
xml: <%@taglib prefix=”x” uri=”http://java.sun.com/jsp/jstl/xml” %>

The uri is simply an identifier of the tag set. The prefix is determinable by the user, but the prefixes seen here are standard.

TLD tags and functions c: core fmt: formatting fn: functions x: xml
c:catch
c:choose
c:forEach
c:forTokens
c:if
c:import
c:otherwise
c:out
c:param
c:redirect
c:remove
c:set
c:url
c:when
fmt:bundle
fmt:formatDate
fmt:formatNumber
fmt:message
fmt:param
fmt:parseDate
fmt:parseNumber
fmt:requestEncoding
fmt:setBundle
fmt:setLocale
fmt:setTimeZone
fmt:timeZone
fn:contains()
fn:containsIgnoreCase()
fn:endsWith()
fn:escapeXml()
fn:indexOf()
fn:join()
fn:length()
fn:replace()
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()

x:choose
x:forEach
x:if
x:otherwise
x:out
x:param
x:parse
x:set
x:transform
x:when

These and other tag systems are used in JSP in one of two forms:

<tag-prefix:type attribute1=”VALUE1″ …

or, as functions to create expressions:

tag-prefix:function(arg1,arg2,…)

As in XML, tags can be complete, using a single tag ending with “/>“, or in pairs, containing a content terminated by a matching ending tag </tag-prefix:tag-type>. Some example of the common usages of the “c” tags are these:

<c:out value=”…” escapeXml=”true”/>
<c:set var=”x” value=”…” />
<c:if test=”…” > … </c:if>
<c:forEach var=”x” items=”…” > … </c:forEach>

Expression Language (EL)
The syntax for what replaces the “…” above is specified by a Java-like language, unimaginately called Expression Language (EL). EL is part of JSP; its expressions are all surrounded by the syntax ${ }. but typically can only be used most effectively in conjunction with JSTL tags. EL is closely related to Java but has some extensions and conceptual simplifications. In particular, EL is more like other web script languages being loosely typed along with other semantic simplifications. EL expressions permit variables and most of the usual arithmetic and boolean operators. Here are some points:

The == operator for strings functions like the Java .equals operator.
an EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string.
EL has a unary operator empty: empty(x) acts like the expression x==null but also means “x equals the empty string”.
the operators or, and are synonyms for ||, &&, respectively.
Query parameters
The value of the parameter “xx” is expressed by the EL expression param.xx. When used directly in HTML,

${param.xx}

is equivalent to the JSP expression:

<%= (request.getParameter(“xx”) != null) ? (request.getParameter(“xx”) : “” %>

Session variables are EL variables
A session variable x automatically becomes available as an EL variable, e.g. if we have:

<%
session.setAttribute( “x”, “hello” );
// or
pageContext.setAttribute( “x”, “hello” );
%>

x = ${x} <!– prints: x = hello — >

JSP beans in JSTL
The EL language provides a simplified syntax for accessing bean’s get/set accessor functions. For example, the bean we use in the examples below is this:

<jsp:useBean id=”mb” class=”bean.MyBean” />

from the class:

——————————————————————————– bean/MyBean.java

package bean;

public class MyBean {
private String count;
public String getCount() { return count; }
public void setCount(String count) { this.count = count; }
public MyBean() {
System.out.println(”MyBean intialized”);
count = “0?;
}
}
EL treats the expression ${mb.count} as the value of mb.getCount(). A typical JSTL tag statement is something like

<c:set var=”i” value=”${mb.count}” />

The c:set tag is also used to call the set member function as follows:

<c:set target=”${mb}” property=”count” value=”5″ />

is equivalent to mb.setCount(”5?). Caution: If you use both set and get property, they must be consistent. For example, suppose you have these member functions:

String getSomeProperty() { … }
void setSomeProperty(int n) { … }

Then EL will consider this a mismatch and most likely reject the setter member function if you tried to use:

<c:set target=”${mb}” property=”someProperty” value=”5″ />

We can also remove a bean from the session using the JSTL c:remove tag:

<c:remove var=”mb” />

Data structures: arrays, arrays, maps, sets
Arrays and maps permit access to their collection via indices: arrays via integer indices and maps via key indices. EL regards both of these accesses as syntactically similar using the [ ] operator. For example:

<%
Map<String,String> theMap = new HashMap<String,String>();
theMap.put(“John”, “5”); theMap.put(“Jim”, “7”);
String theArray[] = { “aaa”, “bbb”, “ccc” };

session.setAttribute( “theMap”, theMap );
session.setAttribute( “theArray”, theArray );
%>

${theMap[“Jim”]} <!– same as theMap.get(”Jim”), outputs 7 –>
${theArray[1]} <!– outputs bbb –>

The EL expressions for maps, sets and lists can all print directly. Arrays, as in Java, don’

t print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose:

${fn:join(theArray,”,”)}

Iterating over data structures
In order to iterate over an array, list, map, or set, the c:forEach tag pair serves our interests. Iteration with c:forEach treats arrays, lists and sets identically. For example, this code will iteratively print the elements:

<!– L represents either an array, list or set –>
<c:forEach var=”x” items=”${L}” >
${x}
</c:forEach>

When using a map, the iteration generates Map.Entry pairs. Using the getKey and getValue functions the structure of the JSTL code to iteratively print the key/value pairs looks like this:

<!– M is a map –>
<c:forEach var=”x” items=”${M}” >
${x.key}: ${x.value}
</c:forEach>

Choice tags c:if, c:choose/c:when
The c:if tag generates a choice situation with a syntax like:

<c:if test=”${EL_BOOLEAN_EXPRESSION}” > … </c:if>

The EL_BOOLEAN_EXPRESSION uses the usual boolean operators with simplifications and additions as mentioned above. If-else structures are based on the c:choose/c:when/c:otherwise tags:

<c:choose>
<c:when test=”${EL_EXPR1}”> … </c:when>
<c:when test=”${EL_EXPR2}”> … </c:when>

<c:otherwise> … </c:otherwise>
</c:choose>

User-generated tag functions
If one wants to avoid explicit JSP sections of code then the Java classes and functions must be able to be accessed through the tag system. Beans provide a limited way of doing so through combinations of “get/set” member functions, but this is not intended for utility functions to manipulate objects. The fn tags provide some of these utility functions, but one can imagine that soon there would be need for your own specific utility functions. Towards this end, JSP provides a means to add your own tag libraries using a combination of Java classes and Tag Library Definition (TLD) files. Both XML-like tags and EL function tags can be added, but it’s much easier to create user-defined EL function tags. The utility functions used must be static functions. For example, suppose we want to use the function defined in this class in an EL expression.

——————————————————————————– mytaglib/MyFunctions.java

package mytaglib;
import java.util.*;
public class MyFunctions {
public static boolean contains(Set<String> set, String target) {
return set.contains(target);
}
}
The glue which connects this functions to JSP is the XML file MyTags.tld held stored in the /WEB-INF/ project directory.

——————————————————————————– MyTags.tld

<?xml version=”1.0? encoding=”UTF-8??>
<taglib version=”2.0? …>
<tlib-version>1.1</tlib-version>
<uri>/WEB-INF/MyTags</uri>
<function>
<name>contains</name>
<function-class>mytaglib.MyFunctions</function-class>
<function-signature>
boolean contains(java.util.Set,java.lang.String)
</function-signature>
</function>
</taglib>
This file defines a uri by which it is accessed and a set of function prototypes in XML format. Each function has a tag name, the class it belongs to and the actual function prototype within this class. The necessary specification within the JSP file is something like this:

<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

The prefix chosen specifies how the function will be referenced within the EL syntax — it can be anything you want, so long as it doesn’t conflict with another tag set. In this case the function will be prefaced by mtg: as in this example:

<c:if test=”${mtg:contains(someSet,someValue)}” > … </c:if>

Example script
——————————————————————————– index.jsp

<%@ page language=”java” contentType=”text/html;
charset=US-ASCII” pageEncoding=”US-ASCII”%>

<%@page import=”java.util.*”%>

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
<%@taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions”%>
<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

<jsp:useBean id=”mb” scope=”session” class=”bean.MyBean” />

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>
<title>Insert title here</title>
<style>
h4 { color: red; margin-bottom:0px; text-decoration: underline; }
</style>
</head>
<body>
<%
String x = “testing”;
String[] a = { “xx”, “yy”, “zz” };

Map<String, String> m = new LinkedHashMap<String, String>();
m.put(”aa”, “1?);
m.put(”bb”, “2?);
m.put(”cc”, “3?);

List<String> l = new ArrayList<String>();
l.add(”nn”);
l.add(”mm”);
l.add(”oo”);
Set<String> s = new LinkedHashSet<String>();
s.add(”aa”);
s.add(”bb”);
s.add(”cc”);
session.setAttribute(”x”, x);
session.setAttribute(”a”, a);
session.setAttribute(”m”, m);
session.setAttribute(”l”, l);
session.setAttribute(”s”, s);
%>
<h4>access values of query parameter p</h4>
<c:if test=”${param.p == null}”>param.p not defined<br /></c:if>
first value: ${param.p}<br />
all values: ${fn:join(paramValues.p,”,”)}

<h4>print objects</h4>
x: ${x}<br />
m: ${m}<br />
s: ${s}<br />
l: ${l}<br />

<h4>print array using join</h4>
a: ${fn:join(a,”,”)}
<br />

<h4>access individuals of array or map via [ ]</h4>
a[1]: ${a[1]}
<br />
m[“bb”]: ${m[“bb”]}
<br />

<h4>access individuals in c:forEach loop</h4>
a: <c:forEach var=”i” items=”${a}”>${i} </c:forEach><br />
s: <c:forEach var=”i” items=”${s}”>${i} </c:forEach><br />
l: <c:forEach var=”i” items=”${l}”>${i} </c:forEach><br />
m: <c:forEach var=”i” items=”${m}”>${i.key}=>${i.value} </c:forEach><br />

<h4>using c:set and escapeXml</h4>
<c:set var=”k” value=”<b>bold</b>” />
k: ${k}<br />
escaped(k): ${fn:escapeXml(k)}<br />
c:out escaped: <c:out value=”${k}” escapeXml=”true” />

<h4>using a bean’s get and set properties indirectly</h4>
mb.count: ${mb.count}:
<c:set target=”${mb}” property=”count” value=”${mb.count + 1}” />
<c:choose>
<c:when test=”${mb.count > 6}”>
became bigger than 6, re-initialize mb
<c:remove var=”mb” />
</c:when>
<c:when test=”${mb.count > 3}”>became bigger than 3</c:when>
<c:otherwise>no more than 3</c:otherwise>
</c:choose>

<h4>User defined tag functions</h4>
s: ${s}<br />
<c:set var=”t” value=”cc” />
s.contains(${t}): ${mtg:contains(s,t)}<br />
<c:set var=”t” value=”dd” />
s.contains(${t}): ${mtg:contains(s,t)}

</body>
</html>

JavaScript xsd validation and examples

<SCRIPT LANGUAGE=”JavaScript”>
var sOutput = validateFile(“sc-valid.xml”);
alert(sOutput);

function validateFile(strFile)
{
// Create a schema cache and add books.xsd to it.
var xs = new ActiveXObject(“MSXML2.XMLSchemaCache.4.0”);
xs.add(“urn:books”, “sc.xsd”);

// Create an XML DOMDocument object.
var xd = new ActiveXObject(“MSXML2.DOMDocument.4.0”);

// Assign the schema cache to the DOMDocument’s
// schemas collection.
xd.schemas = xs;

// Load books.xml as the DOM document.
xd.async = false;
xd.validateOnParse = true;
xd.resolveExternals = true;
xd.load(strFile);

// Return validation results in message to the user.
if (xd.parseError.errorCode != 0)
{
return(“Validation failed on ” + strFile +
“n=====================” +
“nReason: ” + xd.parseError.reason +
“nSource: ” + xd.parseError.srcText +
“nLine: ” + xd.parseError.line + “n”);
}
else
return(“Validation succeeded for ” + strFile +
“n======================n” +
xd.xml + “n”);
}

</SCRIPT>
=========================

File: sc-valid.xml
——————-
<?xml version=”1.0″?>
<x:catalog xmlns:x=”urn:books”>
<book id=”bk101″>
<author>Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</x:catalog>

—————————–
File: sc.xsd
—————————–
<xsd:schema xmlns:xsd=”http://www.w3.org/2001/XMLSchema”
targetNamespace=”urn:books”
xmlns:b=”urn:books”>
<xsd:element name=”catalog” type=”b:CatalogData”/>
<xsd:complexType name=”CatalogData”>
<xsd:sequence>
<xsd:element name=”book”
type=”b:bookdata”
minOccurs=”0″
maxOccurs=”unbounded”/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name=”bookdata”>
<xsd:sequence>
<xsd:element name=”author” type=”xsd:string”/>
<xsd:element name=”title” type=”xsd:string”/>
<xsd:element name=”genre” type=”xsd:string”/>
<xsd:element name=”price” type=”xsd:float”/>
<xsd:element name=”publish_date” type=”xsd:date”/>
<xsd:element name=”description” type=”xsd:string”/>
</xsd:sequence>
<xsd:attribute name=”id” type=”xsd:string”/>
</xsd:complexType>
</xsd:schema>

Post Your site to search engines

How to Post Your site to search engines

Click on the below links and post your site to top most search engines

  1. http://www.google.com/addurl/
  2. http://submit.search.yahoo.com/free/request/
  3. http://search.msn.com/docs/submit.aspx
  4. https://adwords.google.com/select/
  5. http://static.wc.ask.com/en/docs/about/webmasters.shtml#18
  6. http://www.gigablast.com/addurl

Search Engine Statistics – What Market Share?

2008 April: According to 2008 March figures from Hitwise

  1. Google has the largest market share of U.S. based web searches at 67%
    • 2008 February 66.44%
    • 2008 January 65.98%
    • 2007 December 65.98%
    • 2007 November 65.10%
    • 2007 October 64.49%
    • 2007 September 63.55%
    • 2006 October 60.94%
  2. Yahoo is second with a market share of 20%
    • 2008 February 20.59%
    • 2008 January 20.94%
    • 2007 December 20.88%
    • 2007 November 21.21%
    • 2007 October 21.65%
    • 2007 September 22.55%
    • 2006 October 22.34%
  3. MSN is third with a market share of 7%
    • 2008 February 6.95%
    • 2008 January 6.90%
    • 2007 December 7.04%
    • 2007 November 7.09%
    • 2007 October 7.42%
    • 2007 September 7.83%
    • 2006 October 10.72%
  4. Ask is fourth with a market share of 4%
    • 2008 February 4.16%
    • 2008 January 4.21%
    • 2007 December 4.14%
    • 2007 November 4.63%
    • 2007 October 4.76%
    • 2007 September 4.32%
    • 2006 October 4.34%

Source: Hitwise Press Releases

Web Site Designing and publishing

Free Hit Counters

  1. http://my.statcounter.com
  2. http://easyhitcounters.com
  3. http://www.statssheet.com
  4. http://www.neoworx.net

Free Maps on Your Site

  1. http://clustrmaps.com
  2. http://www.ip2map.com
  3. http://www.neoworx.net

Free Site Stats Reports

  1. http://my.statcounter.com/
  2. http://www.statssheet.com

Track the location of visitor

  1. http://www.ip2phrase.com/
  2. http://my.statcounter.com/
  3. http://www.neoworx.net/

Web Master Tools

  1. https://www.google.com/webmasters

Live Cricket On your Site

  1. http://www.vcricket.com

Free Web Site Hosting

  1. www.blogspot.com
  2. www.googlepages.com
  3. www.50megs.com
  4. www.geocities.com
  5. www.netfirms.com

PHP – Ubuntu 9.04 + PHP5 + GD2

It all started when I decided to optimize image slicing algorithm for a new feature on UMapper – and since GD is quite RAM-intensive, I needed to check actual memory consumption, and the obvious choice to do so was PHP’s memory_get_usage() function. However, it failed to produce accurate results – it seemed like images loaded into memory weren’t accounted by the function (RAM was still used :) ).
As it turned out, whoever prepared official php5-gd package, compiles against original GD, and not using PHP5 bundled version of the library. I actually wasn’t aware about the fork, but here is explanation from GD Official Site:

The PHP version of gd offers features similar to and sometimes in addition to those included in the latest version of gd found here as well as many bug fixes not present in the latest GD release. If you are working with PHP, using the built-in gd of PHP 4.3.0 or better is recommended.

We are working to merge the changes done in the PHP GD in the normal GD library.

Well, I was pretty sure that unexpected behavior was caused by using original GD library instead of bundled one. So I decided to remove php5-gd package, recompile php5 from sources, and install updated GD package – which is exactly what gets bundled with PHP5 on other distributions.

Google is my friend, so here is a walkthrough:

# Install build tools, debian helpers and fakeroot
apt-get install build-essential debhelper fakeroot
# Get PHP source (it should go into /usr/src)
cd /usr/src
apt-get source php5
# Install all packages required to build PHP5
apt-get build-dep php5

#Now what we need is to update compile options,
# so we need to edit debian/rules file:
cd php5-5.2.6.dfsg.1
vim debian/rules
# locate the line having “–with-gd=shared,/usr –enable-gd-native-ttf \”
# replace with “–with-gd=shared –enable-gd-native-ttf \”
# that’s remove reference to /usr so that bundled library is used

# compile (drink some coffee, walk you dog, see the latest House episode)
dpkg-buildpackage -rfakeroot

# install the new php5-gd package
cd ..
dpkg -i php5-gd_5.2.6.dfsg.1-3ubuntu4.2_i386.deb

# finally restart apache
/etc/init.d/apache2 restart

That’s it – you should be able to see «bundled» near the GD version in the phpinfo() output. Well, that’s not the only gain – it solves problem with memory_get_usage() as well :)

Now, once I had memory_get_usage() working correctly, back to optimization..