Using the window.open method ? 3 methods to open window

Using the window.open method — 3 methods to open window

Using the window.open method

The syntax of the window.open method is given below:

open (URL, windowName[, windowFeatures])

URL
The URL of the page to open in the new window. This argument could be blank.

windowName
A name to be given to the new window. The name can be used to refer this window again.

windowFeatures
A string that determines the various window features to be included in the popup window (like status bar, address bar etc)

The following code opens a new browser window with standard features.

window.open ("http://www.javascript-coder.com","mywindow");

Note: The popups created using ‘window.open()’ can get blocked by popup blockers.
Click here to find out how to create popups that does not get blocked.

Changing the features of the Popup

You can control the features of the popup using the last argument to the window.open method. The following code opens a window with a status bar and no extra features.
window.open ("http://www.javascript-coder.com","mywindow","status=1");

The code below opens a window with toolbar and status bar.
window.open ("http://www.javascript-coder.com",
"mywindow","status=1,toolbar=1");

The table shows the features and the string tokens you can use:

status

The status bar at the bottom of the window.

toolbar

The standard browser toolbar, with buttons such as Back and Forward.

location

The Location entry field where you enter the URL.

menubar

The menu bar of the window

directories

The standard browser directory buttons, such as What’s New and What’s Cool

resizable

Allow/Disallow the user to resize the window.

scrollbars

Enable the scrollbars if the document is bigger than the window

height

Specifies the height of the window in pixels. (example: height=’350′)

width

Specifies the width of the window in pixels.

Examples
The following code opens a window with menu bar. The window is resizable and is having 350 pixels width and 250 pixels height.
window.open ("http://www.javascript-coder.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");

Example 1

A window with location bar, status bar, scroll bar and of size 100 X 100
window.open ("http://www.javascript-coder.com",
"mywindow","location=1,status=1,scrollbars=1,
width=100,height=100");

Example 2

Moving the window to a desired location

You can use the window.moveTo function to move the popup window to a desired location.
The code below shows positioning the popup at a desired location

function mypopup()
{
mywindow = window.open ("http://www.javascript-coder.com",
"mywindow","location=1,status=1,scrollbars=1,
width=100,height=100");
mywindow.moveTo(0,0);
}

The code positions the popup on the top left corner of the screen.

Putting it all together

Now we will combine all these information to create the popup windows of different types.
The Code below opens a popup window when you enter the page:

<html>
<head>
<title>JavaScript Popup Example 3</title>
</head>
<SCRIPT language="JavaScript1.2">
function poponload()
{
testwindow= window.open ("", "mywindow",
"location=1,status=1,scrollbars=1,width=100,height=100");
testwindow.moveTo(0,0);
}
</SCRIPT>
<body onload="javascript: poponload()">
<H1>JavaScript Popup Example 3</H1>
</body>
</html>

Notice that the URL is kept blank. This will open a blank window. You can see the code in work in this file:
JavaScript Popup Example 3

Popup On Exit

The following code pops up a window when the user exits a page.

<html>
<head>
<title>JavaScript Popup Example 3</title>
</head>
<SCRIPT language="JavaScript1.2">
function exitpop()
{
my_window= window.open ("",
"mywindow1","status=1,width=350,height=150");
my_window.document.write('<H1>Popup Test!</H1>');
}
</SCRIPT>
<body onunload="javascript: exitpop()"
>
<H1>JavaScript Popup Example 4</H1>
</body>
</html>

The code contains an extra line:
my_window.document.write('<H1>Popup Test!</H1>')
This code displays a line ‘Popup Test!’ in the popup.

The code is available in the file:
JavaScript Popup Example 4

The next page shows you how to close a popup window

Creating Portlets for Web Sites With the NetBeans IDE

A portal is a web page that contains individual and customizable web applications. For example, My Yahoo is a portal page. The portal provides value-added services, such as single sign-on, customization, content aggregation, and localization.

Individual web applications that are added to the portal page are called portlets. A portlet is a Java technology web component that is based on the JSR 168 specification and JSR 286, which includes Web Service for Remote Portlets (WSRP). Portlets are managed by portlet containers that supply dynamic content. Portals employ portlets as pluggable user-interface components that provide users with desired content such as RSS feeds, mashups of services such as the current weather in a given area, or even static content such as a group of hyperlinks.

In the past, creating portlets was a complex process. Now, you can quickly and easily create and test portlets using the NetBeans IDE 6.0 and the OpenPortal Portlet Container 2.0 Beta 2. Deploying the portlets onto the server is also simple.

This article shows you how to create portlets and provide dynamic content through drag-and-drop widgets in the NetBeans IDE. The example portlet in this article uses the jMaki Tabbed View widget, pulls in RSS feeds, and uses static links from the New to Java Programming Center.

What You Need to Get Started

To create and test portlets, you need the following software installed on your computer:

For instructions on installing the OpenPortal Portlet Container 2.0 Beta 2, see the installation page. You must download and install the OpenPortal Portlet Container before you follow the next steps.

The portlet container works similarly to servlet containers. A portlet container does the following:

  • Provides the runtime environment for portlets
  • Manages the life cycle of portlets
  • Provides persistent storage for storing portlet preferences
  • Caches the portlets
  • Receives requests from the portal to execute requests on the portlet

Once you have installed the necessary software, start the NetBeans IDE. Next, install the portlet and portlet container plug-ins by following these steps:

  1. Go to Tools in the main menu.
  2. Select Plug-ins.
  3. Click on the Available Plug-ins tab.
  4. Check the boxes for Portlets, the OpenPortal Portlet Container, and jMaki Ajax Support.
  5. Click the Install button and follow the directions from there. You may need to accept a few licenses before the installation process can complete.

Lastly, add the OpenPortal Portlet Container server:

  1. Go to Tools in the main menu.
  2. Select Servers.
  3. Click on Add Server.
  4. Select OpenPortal Portlet Container 2.0 from the list.
  5. Click Next.
  6. Use Browse to set the location in which to install the GlassFish application server. You may need to search your system separately to discover where the NetBeans IDE installed the GlassFish application server.
  7. Click OK.

You are now ready to create a portlet.

Creating a Portlet Project

As you do whenever you create an application in the NetBeans IDE, go to File > New Project, and choose Web > Web Application, then click Next. For the name of this project, type New2JavaPortlet. In the Server drop-down menu, choose OpenPortal Portlet Container 2.0 Beta, then click Next. In the next screen, check the jMaki Ajax Framework box. In the lower half of the pane, you get a selection of layouts. Scroll to the bottom, and choose No CSS Style.

Lastly, at the top of the screen, check the Portlets Support box. Use the Portlet Version drop-down menu and select 2.0, then check the Create Portlet box. In Portlet Class Name, type New2JavaPortlet. Note that the project name and the portlet name must be the same. The other fields are filled in automatically. Click Finish.

Because of the way that portlets are set up within the container, you will not need the displayed index.jsp page. On the left side of the screen, under the Projects tab, you see index.jsp listed. Right-click on index.jsp and select Delete. The file you are going to work on is named New2JavaPortlet_view.jsp. You can find that file by expanding the WEB-INF directory, then the jsp directory. Double-click the file name New2JavaPortlet_view.jsp The file now opens in the workspace.


How the Java Portlet Works

Even though all you’ve done is create a portlet project, the NetBeans IDE has already written an essential class for you. From the Projects tab, expand the Source Packages. Then expand com.text, and open the file New2JavaPortlet.java by double-clicking the file name.

The New2JavaPortlet extends a GenericPortlet class, which is provided, that implements the render() method and delegates the call to more specific methods to display the portlet based on its mode. Developers can extend GenericPortlet and implement as many of the following specialized render methods as are necessary for their portlet:

  • doView() Called by render() when the portlet is in View mode. Intended to contain logic that displays the View page for the portlet.
  • doEdit() Called by render() when the portlet is in Edit mode. Intended to contain logic that displays the Edit page for the portlet.
  • doHelp() Called by render() when the portlet is in Help mode. Intended to contain logic that displays the Help page for the portlet.

Notice that the New2JavaPortlet calls these methods, locating the pages for each. In this article, you will put the content of the portlet in the View page through drag-and-drop widgets and some HTML code. But you can extend this GenericPortlet cl

ass for other portlets. You can also go back later and modify the Edit or Help page. Once you have had a good look at the New2JavaPortlet class, you can close it.

When you build and run the portlet, the browser will display the New2JavaPortlet_view.jsp. Currently, this page contains only the static text: New2JavaPortlet – VIEW MODE. Because it is a JavaServer Pages (JSP) technology page, you can add any scripts or JSP tag libraries that you wish, and treat it like any other JSP page.

Test your portlet environment now before adding more content: From the main menu, click Build and select Build Main Project. Once the build is successfully completed, go to the main menu and click Run. Select Run Main Project. This takes a little longer as the application server is started, the portlet container is started, and a browser window is opened.

Notice that the portlet project name is the same as the portlet itself. Once you see that your development and testing environments are working properly, you can add content to replace the static text on the New2JavaPortlet_view.jsp page. To see the changes that you make to your portlet, you undeploy and deploy the portlet, as explained in the next section.

Adding Dynamic and Static Content to the Portlet

Because this portlet will contain several kinds of content, organize the content for a small area on a web page by using tabbed panes. You can choose other types of layouts, of course, but for this example, use the jMaki widget named Tabbed View. On the right side of your screen, notice that you have many available widgets to drag and drop. Check to be sure that the jMaki Yahoo widgets list is expanded .

Within the workspace page, delete the static text that says New2JavaPortlet - VIEW MODE. Also, delete the surrounding HTML code for bold: <b></b>. Now drag and drop the Tabbed View widget, shown highlighted in white , from the palette onto the page, exactly where you have just deleted text. Once you have dropped the Tabbed View widget onto the page, the following code appears on the page:

<a:widget name="yahoo.tabbedview"
   value="{items:[
           {label : 'My Tab', content : 'Some Content'},
           {id : 'bar', label : 'My Tab 2', include : 'test.jsp ', lazyLoad : true },
           {label : 'My Tab 3', content : 'More Content',  selected : true}
          ]
         }" />

The action of dragging and dropping a jMaki widget onto the page causes the creation in the resources directory of all the files necessary to build that widget.

To get an idea for how this widget works, save the file. Next, right-click the project name in the Projects pane and select Undeploy and Deploy. Once it is built, run the project: Go to the main menu, click Run, and select Run Main Project. When the project runs, your changes appear in the browser window. Click on each of the tabs in the Tabbed View pane. Notice on the tab named My Tab 2 that the file test.jsp was not loaded. This is only because a test.jsp had not been created, but it does demonstrate how you call a JSP page to appear in the pane.

For the New2JavaPortlet, you are going to create new JSP pages that the widget will call. Each of these pages provides the content for each of the tabs. On the New2JavaPortlet_view.jsp page, replace the code shown earlier with the following code:

<a:widget name="yahoo.tabbedview"
   value="{items:[
           {id : 'bar', label : 'Popular & New', include : '/New2JavaPortlet/whatsnew.jsp ', selected : true },
           { label : 'Java Fundamentals', include : '/New2JavaPortlet/fundamentals.jsp ', lazyLoad : true },
           { label : 'Downloads', include : '/New2JavaPortlet/downloads.jsp ', lazyLoad : true },
          ]
         }" />

This code calls three JSP pages: whatsnew.jsp, fundamentals.jsp, and downloads.jsp.

The next step is to create those pages. In the Projects pane, right-click on Web Pages. Then select New, and lastly JSP. Notice that you are saving these pages into the Web Pages directory, not the jsp directory that the portlet container created for the New2JavaPortlet_view.jsp. Any JSP pages that you create must go into the Web Pages

Create three JSP pages in this manner, naming them whatsnew, fundamentals, and downloads. The NetBeans IDE automatically adds the .jsp extension, so don’t include that in the file name.

Next, run Undeploy and Deploy again. Then click on the Run menu, and select Run Main Project. This time, note that the tab names have changed. As you click on each tab name, you get the JSP pages that you just created because of the code you replaced. Open each of these JSP pages — downloads.jsp, fundamentals.jsp, and whatsnew.jsp — and add content as described in the following subsections.

The downloads.jsp Page

This page contains simple static content, a title, and a list of links. Do not change the first two lines of code that appear at the top of the page:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

But replace all of the HTML code with the following:

<h3>Downloads for New Developers</h3>
 
<ul>
  <li><a href="http://java.sun.com/javase/downloads/i">Java SE (JDK)</a>
  <li><a href="http://www.netbeans.org/">NetBeans IDE</a>
  <li><a href="http://www.mysql.com">MySQL Database</a>
</ul>

The fundamentals.jsp Page

This page will provide dynamic content, pulling in an RSS feed. Again, leave the first two lines of code alone, and remove all of the HTML code. Next, from the jMaki Widgets palette on the right side of the display, drag and drop the Block List widget onto the page.

The following code should appear on your page:

<a:widget name="jmaki.blockList" value="[
{title : 'jMaki Project Home', link : 'https://ajax.dev.java.net', description : 'Where to go for the latest jMaki.' },
{title : 'jMaki Widgets Home', link : 'https://widgets.dev.java.net', description : 'The source for the latest jMaki widgets.' },
{title : 'jMaki-Charting Home', link : 'https://jmaki-charting.dev.java.net', description : 'Enables complex charts rendered on the client in any modern browser.' }
]"  />

The widget prov

ides placeholder text only. Replace everything with the following code:

<h3>Java Technology Fundamentals</h3>
 
<a:widget name="jmaki.blockList" service="/xhp?id=rss"  />

In order to populate the widget with data from an external service, such as an RSS feed, you must replace the value attribute with service="/xhp?id=rss". If any page consists of a jMaki widget, then the jMaki runtime is bundled with the application. The runtime consists of jmaki.xhp.XmlHttpProxyServlet class that maps to the /xhp URL pattern within the application context.

The identifier or ID specified in the URL, rss, is configured in a configuration file named xhp.json. This file consists of a list of default external services that the widgets in a page can access. You can specify each entry in the xhp.json file by using up to five different parameters:

  • ID: This required parameter is a unique identifier for the entry.
  • URL: This required parameter gives the location of the external service.
  • Parameters: These optional parameters specify the default values passed to the URL.
  • API key: This is an optional parameter to invoke the service with a specific key.
  • Stylesheet: This is an optional parameter to process the response.

Next, you must change the xhp.json file. Go to the Projects tab and expand the resources directory. Double-click the file xhp.json, and scroll to the bottom of that page. Search for this code in the xhp.json file:

{"id": "rss",
      "url":"http://weblogs.java.net/blog/ludo/index.rdf",
      "xslStyleSheet": "rss.xsl"
  }

The tag and the default entry tell the jMaki runtime to fetch the RSS feed from http://weblogs.java.net/blog/ludo/index.rdf, apply the rss.xsl stylesheet — which understands the multiple RSS/Atom formats — to the received response, and convert the data into a common JavaScript Object Notation (JSON) data format of the type "dataType" : "jMakiRSS". The jMaki Block List widget can convert jmakiRSS data to its specific data model.

But the intention of this article is not to pull in Ludovic Champenois’s blog. So change the URL of http://weblogs.java.net/blog/ludo/index.rdf to http://blogs.sun.com/JavaFundamentals/feed/entries/rss.

Additionally, you will pull in another feed on the whatsnew.jsp page, so change the URL in the code as shown in the following code snippet. The new URL is highlighted in red.

{"id": "rss2",
      "url":"http://blogs.sun.com/new2javaUpdates/feed/entries/rss",
      "xslStyleSheet": "rss.xsl"
   }

Notice that the ID for the second RSS feed to pull in is named rss2. Notice also that the URL pulls in the blogs from the “What’s New” section of the New to Java Programming Center. Save the xhp.json file. Because you’ve added another block of code to pull in the second feed, you must separate the two
with a comma after the closing curly bracket (}) of the first block. The following code snippet shows the added comma in red on the fourth line:

    {"id": "rss",
      "url":"http://blogs.sun.com/JavaFundamentals/feed/entries/rss",
      "xslStyleSheet": "rss.xsl"
     },
    {"id": "rss2″,
      "url":"http://blogs.sun.com/new2javaUpdates/feed/entries/rss",
      "xslStyleSheet": "rss.xsl"
     }

The whatsnew.jsp Page

Go to the whatsnew.jsp page, and delete the HTML code. Add the following static HTML code:

<h3>What's Popular</h3>
 
<ul>
  <li><a href="http://java.sun.com/docs/books/tutorial/">The Java Tutorial</a></li>
  <li><a href="http://blogs.sun.com/JavaFundamentals/">Java Technology Fundamentals</a></li>
  <li><a href="http://blogs.sun.com/CoreJavaTechTips/">Core Tech Tips</a></li>
  <li><a href="http://java.sun.com/developer/onlineTraining/tools/netbeans/">Easy Web Site Creation in the NetBeans IDE</a></li>
  <li><a href="http://java.sun.com/javaee/5/docs/tutorial/doc/">The Java EE 5 Tutorial</a></li>
</ul>
 
<h3>What's New</h3>

Next, from the jMaki Widgets palette on the right side of the display, drag and drop the Block List widget onto the page. Change the code as shown here:

<a:widget name="jmaki.blockList" service="/xhp?id=rss2"  />

Customizing the jMaki Widgets

All the files that you need for customizing any of the widgets are available in the resources directory by widget name. In this case, look under jMaki for the files for the block list. Expand the blocklist directory, and open the file called component.css.

Change the line that says height : 85px; to height : 25px; and save the file.

Next, open the component.html file, and delete the following code from it:

<br/>
@{description}<br/>

This removes the descriptions from the RSS feeds, leaving only the title as a link. You can also add content, such as a date, by adding it to this file. Now, save all the files, click Undeploy and Deploy, then run the portlet again by clicking on Run in the menu and selecting Run Main Project.

Again, click Undeploy and Deploy. Then click Run the application. You now see the pages that you

‘ve created with the content. Notice also that the block list is taking up a lot of room. You can customize jMaki widgets easily by going to the Projects tab, expanding the resources directory, expanding the jMaki directory and then blockList. Edit component.css so that the height is just 25 pixels (25px).

Click Undeploy and Deploy again. When you run the portlet.

Your portlet is now complete. Once the portlet is deployed, users can add the portlet to their portal page and have access to the information they want on their page. You can tailor portlets in many different ways to suit the needs of your web site. The NetBeans IDE provides many widgets that you can drag and drop, but you are not limited by what that palette provides. You can also create your own widgets, or use Java code to create an unlimited number of objects to get the functionality that you want.

The next step is to archive the entire project in a ZIP file and send it to the server administrator. If you are also the server administrator, read the next section.

Packaging and Deployment

The portlet specification specifies the packaging and deployment of portlets as part of standard Web Application Archive (WAR) files that may contain other web components, such as JSP pages and servlets. In addition to the web.xml deployment descriptor now found in WAR files, the portlet.xml file in the WEB-INF directory descriptor defines all portlets and portlet-related configurations. An XML schema included in the portlet specification JSR 168 defines the standard elements for portlet configuration stored in the portlet.xml file.

Each portal-server vendor must provide a tool to parse the portlet descriptor file and deploy the portlet. These tools likely exist in GUI form as well as in command-line form. Developers will be able to integrate the command-line deployment tools with the Apache Ant tool. This creates additional development environment possibilities, because most development tools provide an interface for Apache Ant.

To deploy the project onto the server, see the documentation for your portal server for complete details. Most portal servers will allow you to deploy the WAR file, which is located in your project’s dist directory after you perform a build. Depending on your portal server, this may be deployed by using the Ant command, copying the WAR to your portal autodeploy directory, or using the administrative feature of your portal server.

Summary

Now that you have created a portlet, you can create other types of portlets for the portal page for your users. Portlets can include components such as local weather, the latest news, live sports scores, maps, and RSS feeds from other sites. Portlets allow your users to customize the web page to meet their specific needs, and this keeps them coming back to your web site.

For More Information

JavaFX as Rich Internet Application Platform

JavaFX as Rich Internet Application Platform

JavaOne wrapped up on Friday. We hosted individuals from across the globe, and from every industry: consumer electronics and gaming, to enterprise IT, space exploration, factory automation, the automotive industry, academia – like the network itself, Java delivers something for nearly everyone, everywhere.


This year’s biggest announcements centered around Java’s role in the future of rich internet applications (or RIA’s). What’s a rich internet application? It depends on your perspective – from mine, it’s any network connected application that persists in front of a user, typically outside a browser, that can operate when disconnected from the network.

On the one hand, I’d claim Java’s always been a RIA platform – before the world really wanted one. Early Java applets delivered interactivity, but at the expense of development complexity and, in the early days, performance – when a browser, and more recently Javascript, would suffice.

But browser based applications are hitting complexity and performance limits, and content owners are striving for higher levels of engagement (via high definition video, or advanced interactivity). Developers are demanding something new – the browser’s a wonderfully accessible programming model, but it’s a weak deployment model for rich/disconnected applications.

An unspoken driver of RIA is also business model evolution – many companies behind rich applications are seeking independence from browsers and search engines, whose default settings and corporate parents present a competitive threat. There’s a growing appetite for locally installed applications that build rich, direct and permanent engagement with consumers. No one wants to pay a toll to meet their own customers.

With that in mind, as we looked to reinvent the Java platform, we heard a consistent set of requirements. And not just from coders, but from sports francishes seeking to directly engage their fans, media companies wanting to bypass browser defaults, to artists and businesses and device manufacturers – everyone’s looking to uniquely engage consumers via the network. These audiences have nearly identitical requirements for a RIA platform – they want technology that:

  • Reaches every internet consumer – on desktops, mobile, and new devices, too.
  • Delivers high performance – and the ability to engage creative professsionals in the design process.
  • Leverages existing skills and enterprise infrastructure.
  • Is totally free, and open source.
  • Provides content owners with control and ownership of their own data.

At JavaOne last week, we addressed every one of those issues – here’s how:

First, RIA developers want to reach every consumer on earth, and on every device.

Why? Because the market is in front of consumers – no matter what screen they may be using. Desktop, mobile phone, personal navigation, digital book – you name it. The market’s in front of all the screens in your life, not just a PC.

That said, on PC’s alone, Java’s popularity has grown in the last few years, as measured by runtime downloads – we routinely download 40 to 50 million new Java runtimes a month, and update more than a billion every year. The adoption of the Java platform exceeds the adoption of Microsoft’s Windows itself – Sun’s Java runtime environment (JRE) is preloaded on nearly every Windows machine (from HP, Dell, Lenovo, etc.), but also runs on Apple’s Macintosh, Ubuntu, Fedora, SuSe, Solaris and OpenSolaris desktops. In addition, a JRE is present on billions – yes, billions – of wireless and mobile devices, from automobile dashboards and navigation devices, to Amazon’s Kindle (did you know Amazon’s Kindle is a Java platform?).

Which is to say, the Java platform reaches more people than any other software technology the world has ever seen.

Second, RIA developers want performance, functionality AND simplicity.

Why? Because content owners and application developers want to engage consumers – and want to engage artists and creative professionals in the workflow.

Java’s history with simplicity isn’t perfect – which is why our teams have rewritten the applet model, and focused so intently on making the new consumer Java runtime environment (download a beta version here) exceptionally fast to load within a web page, exceptionally performant for complex interactivity, and trivially accessible to consumers. We’ve also simplified Java with a scripting language, JavaFX script, that enables creative professionals to engage with coders to create immersive experiences, while embracing the creative tool chain (from interaction design to pixel manipulation) used by the worlds designers and digital artists.

And I’m really pleased we’ve solved the desktop installation problem, by making JavaFX applets separable from a web page with a simple drag and drop (click the image above to watch this demonstrated). Developers can now bypass the browser to trivially install apps on desktops – once the applet’s dropped on the desktop, content owners have a direct relationship with their consumers.

You might have also seen that we’re adding full high quality audio and video codecs to Java on every platform on which it runs – resolving another gap for RIA developers, support for time-based media (click here for a demo of high performance video).

Third, enterprises want to reuse their existing Java skills and assets in moving to RIA.

Nearly every enterprise employs programmers with Java skills – it’s still the number one internet language taught across the world, and found pervasively in global business infrastructure. As businesses move to engage their customers via RIA platforms, reusing existing skills, and connecting RIA’s to existing systems, gives the Java community a unique ability to build from what exists – rather than attempt to replace it.


This familiarity also allows businesses and developer teams to focus on engaging with consumers – rather than irritating IT with new infrastructure requirements (JavaFX developers simply link to existing enterprise infrastructure, vs. requiring new systems for RIA apps).

Fourth, RIA developers want free and open platforms.

Why free? Because developers don’t want to encumber their applications with royalty bearing dependencies, or use technologies that predefine where consumers might appear. You don’t build developer communities around closed source, you build user communities – and this is an instance where developer selection and adoption will define the broadest RIA marketplace. JavaFX will, like all of Sun’s software platforms, be made freely available as open source, and it’ll be released via the GPL (v2) license.

And lest you think free and open software is the province of those with goatees and tattoos… we’re seeing a rising tide of developing nations mandating free and open software in government and academic procurement. Why? To protect choice, and build indigenous opportunity – there’s no reason to build dependencies upon proprietary software if you can avoid it.

Lastly, lets face it, the real value in Web 2.0 is the data – not the app. And that data is YOURS.

If you’ve been watching the social media space as carefully as we have, you understand the value of instrumentation and intentionality in building a business on the web. Knowing what users are doing with your product, whether it’s a fantasy cricket league or a consumer banking application, enables more innovative business models, the delivery of higher value services, placement of more valuable ads – data allows for better decisions, and better value creation (and bluntly put, higher CPA).

But most rich internet applications are built, then deployed – into a fog. Developers who leave the confines of the browser either lose access to information about what their users are doing, or have to rely upon a technology provider that’s inserting itself into their data stream. And some of those technology providers compete with content developers.

With a project code named Project Insight, we’ll be instrumenting the Java platform to enable developers to harvest the data stream generated by their RIA content. JavaFX developers can focus on their business models – rather than enhancing someone else’s.

_______________________

With all that said, what’s the success of JavaFX worth to Sun?

By definition, it’s worth more to Sun than the adoption of someone else’s platform (known as “positive option value”) – and the proprietary infrastructure used to serve it (don’t forget, RIA’s have rich internet back-ends (RIBs?). And in the RIA world, all the options are going to be priced at free, anyways – this isn’t a contest to be won on price.

From where I sit, the platform likely to win will be the one that sets developers free – to pursue markets, opportunities and customer experiences as they define them, not as vendors define them. Now, setting developers free – that’s where we can excel. It’s in the DNA of everything we do.

For developers, learn more at JavaFX.com. And be sure to check out NetBeans – like Java itself, it’s starting to rock the free world…

See also

Simple JavaScript Clock

Simple JavaScript Clock

<SCRIPT Language=”JavaScript”>

<!– hide from old browsers

function jsClock(){

var time = new Date()

var hour = time.getHours()

var minute = time.getMinutes()

var second = time.getSeconds()

var temp = “” + ((hour > 12) ? hour – 12 : hour)

if(hour==0) temp = “12”

if(temp.length==1) temp = ” ” + temp

temp += ((minute < 10) ? “:0” : “:”) + minute

temp += ((second < 10) ? “:0” : “:”) + second

temp += (hour >= 12) ? ” PM” : ” AM”

document.clockForm.digits.value = temp

id = setTimeout(“jsClock()”,1000)

}

//–>

</SCRIPT>

<BODY ONLOAD=”jsClock()”>

<FORM NAME=”clockForm”>

<FONT face=”Courier New,Courier” size=3><B>

<INPUT TYPE=”text” NAME=”digits” SIZE=11 VALUE=”Loading”></B>

</FONT>

</FORM>

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.