<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>All Free Tech &#187; Java</title>
	<atom:link href="http://www.allfreetech.com/category/java/feed" rel="self" type="application/rss+xml" />
	<link>http://www.allfreetech.com</link>
	<description>For developers</description>
	<lastBuildDate>Tue, 27 Jul 2010 13:58:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>My Personal Experience with SCJP Certification</title>
		<link>http://www.allfreetech.com/java/my-personal-experience-with-scjp-certification-574.html</link>
		<comments>http://www.allfreetech.com/java/my-personal-experience-with-scjp-certification-574.html#comments</comments>
		<pubDate>Thu, 01 Jul 2010 14:17:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[Certification]]></category>
		<category><![CDATA[Experience]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[SCJP]]></category>

		<guid isPermaLink="false">http://www.allfreetech.com/?p=574</guid>
		<description><![CDATA[About SCJP 5th 12:00 Sun SCJP certification exam 5th 0 certification validates the ability of applications using Java 2 SE 5 design. 0 technology. Passing this test is essential for you when you get to the Sun Certified Developer for Java 2 Platform (sCJD), Sun Certified Web Component Developer for the J2EE Platform (SCWCD), Sun [...]]]></description>
			<content:encoded><![CDATA[<p>About SCJP 5th 12:00 Sun SCJP certification exam</p>
<p>5th 0 certification validates the ability of applications using Java 2 SE 5 design. 0 technology. Passing this test is essential for you when you get to the Sun Certified Developer for Java 2 Platform (sCJD), Sun Certified Web Component Developer for the J2EE Platform (SCWCD), Sun Certified Business Component Developer (SCBCD), Sun Certified Mobile Application to Developer (SCMAD), Oracle Certified Solution Developer and Oracle Certified Enterprise Developer programs, and Master CIW Enterprise Developer certification. SCJP 5th 0 certification requirements can be a trial</p>
<p>i. e. CX-310 must pass to reach 055, the fifth SCJP 0 certification. Although there are no prerequisites for this certification, it would be helpful if the hands on experience with the basic syntax of the Java programming language. Benefits of SCJP Certification SCJP certification proves your expertise on the Sun Java products and technologies. Experts hold the SCJP certification are preferred by employers, and they also get preference in promotions. want to SCJP certification is helpful for professionals to update their credentials and get recognition from the industry. SCJP Certified professional can find appropriate jobs and simply paid more.</p>
<p>Lets discuss how to prepare for him. </p>
<p>
	Preparation: This is the most important phase of the SCJP. First you need to brush up all your foundation fundamentals in Core Java. You can</p>
<p>following books on this: for Java 5 Study Guide (Exam 310-055) by Katherine Sierra There are many other renew book on Java-based but I would say use as much Java knowledge is enough to clear the sample. Especially book by Katherine Sierra is very important to score more marks in SCJP. You should study all the chapters thoroughly and try to complete all writing questions given at the end. If you give any problem in this paper question the face, should be the end of each chapter, go back and read again the chapter. <br />
	The complete reference is a good book for any requested concept that you missed or can not find in the other book. </p>
<p>	Test Simulator: Here comes the second part, on completion of these two books you need to prepare for the test simulator. This is a very important step because it determines how much you learn and see if you ready for the test or not. After basic in Core Java, you should know where you stand. Test simulator will help you to determine whether to go the right time, in which chapter or topic you are poor and can then go back and help prepare again. <br />
	There&#39;s much simulator on the market, I personally recommend you uCertify Test simulator for SCJP. This is an excellent tool that I found and it helped me a lot in dealing with difficult topics such as generics and collection. Upon completion of the books that I did not know, which is a part of my preparation to be weak and needs improving. I went to test for uCertify, noting that issues such as generics and collection, I am with fewer brands. I went back to book and relate this topic again, and guess what, I better mark in my final exam in generics and collection. <br />
	Thanks uCertify. </p>
<p>	Lets discuss uCertify. </p>
<p>	1 UCertify PrepKit tour of features: </p>
<p>	PrepKit CX310-055, Java 5 0 an interactive software that helps you is to learn, tracks your progress identifies areas for improvements and simulates the actual exam. This PrepKit contains 7 interactive practice tests with over 801 challenging questions guaranteed comprehensively cover all the objectives for the CX310-055: exam. With detailed analysis for each question, over 249 study notes, interactive quizzes, tips and technical articles, this PrepKit ensures that you know a solid understanding of basic technical concepts to ace your certification exam. <br />
	I like best is 100% money-back guarantee, if you do not get certified on the first try is, they become your money back. </p>
<p>
	This is the first screen will prompt you for the purchase and installation, you can find it on your PC. </p>
<p>	7, section practice test will each have 75 questions. They also have diagnostic test of 15 questions, except that it will be a final test with 40 questions. The best part I liked was in the form of 236 question quiz. They also have opportunity to custom tests that you can choose your topic and the number of those, you have a really nice option to the topic<br />
	work </p>
<p>	where you feel you are not strong and need to work on! </p>
<p>	On the right you will find tips and tricks, which turned out to be very helpful SCJP for me was: </p>
<p>
	The complete simulator costs $ 74. 98, I think, worth an investment, as it related to your career and also in comparison to the functions and importance of this test, it is worth money in this. <br />
	a trial version available, you can use to assess their significance, but the purchase is a nice option, since it can offer more and take control of your exam. Below is the difference between trial and final version, as in the website or book. <br />
	Full length interactive tests tricky 1 7 questions with full explaination (inc. Quiz) 15 <br />
	801 Articles, How Tos. . , Tips Study Notes 40 249 Detailed reports and analysis tools, no time limit, no registration No adware, malware or spyware 24&#215;7 Unlimited upgrade up to 1 year unconditional 100% Money-back guarantee 2 How to use uCertify PrepKit effective: </p>
<p>	To start most from uCertify always there after the primary, as I mentioned the books already. Jump directly to non-Simulator. The best way is to first study how Exam tips WECK, study notes, articles and advice. Then for interactive quiz go as they always renew your preparation and get some confidence, if you studied well. Then go for the practice test and weak themes of preparation, a practice test can also help you in this. </p>
<p>	3 What contributed to my success uCertify: </p>
<p>	As I discussed earlier is also the biggest advantage I have received from uCertify, I arrived at my weakest subjects know i. e, Generics and Collection , then I worked on these issues and most problems can be solved on the basis of this. And it has to do me a few days. The tips and materials have helped me a lot to work on final touches to the test. Flash card has helped me, more important point at the last save. Beg best part was personal test by which I include only focus primarily on tests of generics, collection, and concurrency. </p>
<p>	4 My experience with uCertify PrepKit: </p>
<p>	After completing my foundation books by Katherine Sieera, I was for some good test simulator, I can try search. I have a preliminary test simulator, which I really did not like, then told my Firend uCertify me and believe me after the purchase I was very confident. During the test, after half a question I knew I was clear. And all the trust was of my favorite test simulator uCertify. I was afraid before the test because I thought that I might not, but after trying this simulator I was confident. <br />
	Now I&#39;m next after SCJP SCWCD and I already grabbed a copy of uCertify SCWCD simulator to test and would be held soon. </p>
<p>
	Final Touch for Exam: Once your base and simulator will be ready on you will be for the test. just follow these simple tricks just before the test: Book your place and time for the test even before advance. She hunts for them. It is always advisable to test, taking in the morning, you will be fresh not working, studying hard, or just before a night given its more important point in the simulator, just before to revise a day of the test during test test do not panic and always try simple question first special care with matching type of question, as if you try this question again open the previous answer is deleted and you have once again to this question you try drinking water before the test</p>
]]></content:encoded>
			<wfw:commentRss>http://www.allfreetech.com/java/my-personal-experience-with-scjp-certification-574.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java tips &amp; tutorials &#8211; excellent resources for learning Java</title>
		<link>http://www.allfreetech.com/java/java-tips-tutorials-excellent-resources-for-learning-java-313.html</link>
		<comments>http://www.allfreetech.com/java/java-tips-tutorials-excellent-resources-for-learning-java-313.html#comments</comments>
		<pubDate>Thu, 03 Jun 2010 10:08:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[resources]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.allfreetech.com/?p=313</guid>
		<description><![CDATA[If you&#39;re a beginner when it comes to the Java programming language or even if you are an experienced programmer looking for some new tips and tricks, the best thing to do, and which has the advantage of completely free, is search the Internet for Java tips and Java tutorials. instead of buy this, try [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#39;re a beginner when it comes to the Java programming language or even if you are an experienced programmer looking for some new tips and tricks, the best thing to do, and which has the advantage of completely free, is search the Internet for Java tips and Java tutorials. </p>
<p>	instead of buy this, try one or two books, and you will be impressed by the amount of information can be found on the Domain. This is the easiest way to access tons of Java tutorials or a lot of very useful Java tips with no effort and no cost at all. </p>
<p>	The Java programming language and platform have been initiated during the early nineties and developed a few years later she was re-designed for use on the Internet, and since then his popularity has increased greatly, especially on the server side of the Internet. <br />
	Today, a number of Java experts and a lot of documentation has been written on this topic, so if you are a beginner searching for Java tutorials to learn more, and if you is an advanced user, you can always use the large number of Java tips, which are found and can help you solve almost any problem do you encounter on your way to the perfect Java programs. <br />
	<br ablsolute="" about="" and="" are="" as="" attending="" beginners="" better="" courses="" even="" for="" in="" internet="" java="" learning="" on="" the="" tutorials="" /><br />
	. You can do everything from &quot;Getting Started&quot;, the fundamentals of the Java language, essential classes, which are more specialized tutorials such as security in Java, graphics, working with databases and much more. Here you will find websites that give tips in Java and Java tutorials for those who need specialized. Those written tutorials and tips from experts and are grouped into categories that you immediately see the Java or Java-Tutorials Tips you seek help. The best thing is learning to read more Java tutorials, and the Java tutorial, you learn from the short and useful tips you can combine Java. </p>
<p>	On the other hand, if you are an experienced programmer and you want to share your knowledge, you can start writing Java Java tutorials and tips to help the newcomers, and others who need it. <br />
	When writing Java tutorials make sure you make are clear and understandable and that you report on all aspects of the problem. <br />
	Even when writing Java-Tips if you want to find people easily understand the information you provide there are some &quot;rules&quot; should respect the way the selection of the best titles of the Java tip covered exactly what you are presenting, and the best subtitle of the course, the title must expand a bit, you can also write a short summary or comment if you know where you do your Java tips, then do you want to describe in the introduction, the command list, the statements in it and a little conclusion if you wish. You can even include a link to more detailed Java tutorials on this topic. </p>
<p>	Java Java tutorials and tips are the best resource for learning and improvement in Java, so you start searching for them, or start writing one if you are experienced and share want!</p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.allfreetech.com/java/java-tips-tutorials-excellent-resources-for-learning-java-313.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Extract Java File From Sony Ericsson K850?</title>
		<link>http://www.allfreetech.com/java/how-to-extract-java-file-from-sony-ericsson-k850-305.html</link>
		<comments>http://www.allfreetech.com/java/how-to-extract-java-file-from-sony-ericsson-k850-305.html#comments</comments>
		<pubDate>Thu, 03 Jun 2010 06:18:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ericsson]]></category>
		<category><![CDATA[K850]]></category>
		<category><![CDATA[Sony]]></category>

		<guid isPermaLink="false">http://www.allfreetech.com/?p=305</guid>
		<description><![CDATA[the Google Maps have installed on my Sony Ericsson K850 and now wanted to extract the Java file to get during the installation of the Google Map on my phone. I did not think that Java file, as I have installed that Google Map on the phone GPRS facility on their mobile phones. Just as [...]]]></description>
			<content:encoded><![CDATA[<p>the Google Maps have installed on my Sony Ericsson K850 and now wanted to extract the Java file to get during the installation of the Google Map on my phone. I did not think that Java file, as I have installed that Google Map on the phone GPRS facility on their mobile phones. Just as online installation I am not done with that Java file for later use. So there is a way to back up the java file is taking, so I install it again if necessary? <strong> <a href="http://freewebcontents blogspot.. Com/2010 / 04/how-to-extract-java-file-from-Sony. html " onclick="javascript: pageTracker. _trackPageview ('/ Outgoing / article_exit_link');" rel="nofollow"> How to extract Java file from Sony Ericsson K850? </a></strong></p>
<p><strong></strong></p>
<p><strong><a href="http://freewebcontents blogspot.. Com/2010 / 04/how-to-extract-java-file-from-Sony. html " onclick="javascript: pageTracker. _trackPageview ('/ Outgoing / article_exit_link');" rel="nofollow"> Re: Extract File from Java Sony Ericsson K850 <br />
	Yes, you can extract the Java file from Sony Ericsson K850 using the Uploader for the A2-A2 (K850, C902, C905, etc), free working tool. So you must download it first and then you can use it, unpack your Java files from the installation directory. So, use this tool and get theGoogle Map Java file for your future use. You can use this tool on the Internet that is free. But, you download it from trusted sites. <strong> </strong></a><strong><a _trackpageview="" href=" http://freewebcontents blogspot.. Com/2010 / 04/how-to-extract-java-file-from-Sony. html " javascript:="" outgoing="" pagetracker.="" rel="nofollow onclick ="> How to extract Java file from Sony Ericsson K850? </a></strong></strong></p>
<p><strong><strong></strong></strong></p>
<p><strong><strong><a _trackpageview="" href=" http://freewebcontents blogspot.. Com/2010 / 04/how-to-extract-java-file-from-Sony. html " javascript:="" outgoing="" pagetracker.="" rel="nofollow onclick =">Re: Extract File from Java Sony Ericsson K850 <br />
	Hi, you can use Google Maps Java extract from your Sony Ericsson K850 with the use of a few tricks file. You need to use the Explorer for getting the system files. Then you search the hidden files and then use the hidden files for the user JAR file that theGoogle related card. If you save this jar file that only the directory you want. And you continue to use the JAR file when you need it. </p>
<p>	Re: Extract File from Java Sony Ericsson K850 <br />
	I do not think it will be possible to extract an installation file from the phone. As you have installed Google map from the Internet using GPRS, you must re-download the same file by using the Internet. But for the time you have saved the JAR file on yourmobile phone so that you can use it for your future to be allowed. So, make easy use of the Internet forever, that the JAR file and save it. </p>
<p>	Re: Extract File from Java Sony Ericsson K850 <br />
	I am also looking for the similar option that will help me to get the setup of the firmware installed on my Sony Ericsson C902. I&#39;ve searched the web, but get over this not a solution. If anyone knows how to get the extracted files setup applications, from mobile then please give me that. If someone give me the solution, then download the setup files can be avoided again. Please help me. </p>
<p>	Re: Extract File from Java Sony Ericsson K850 <br />
	I do not think that it not be a solution for this. You need to select re-download the same file from the Internet and save it for when the option or how to install them, then Save option and you can ask for the setup file for your particular application. Then you can use the specific file, run if you want. So, there is no other way than downloading the same file to save again, but the choice of the option. Make sure that you save in a position to file that is not under the JAR file extension of the jad extension.</a></strong></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.allfreetech.com/java/how-to-extract-java-file-from-sony-ericsson-k850-305.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Web Application on JBoss AS 5</title>
		<link>http://www.allfreetech.com/java/creating-a-web-application-on-jboss-as-5-136.html</link>
		<comments>http://www.allfreetech.com/java/creating-a-web-application-on-jboss-as-5-136.html#comments</comments>
		<pubDate>Sun, 24 Jan 2010 08:14:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JBoss]]></category>

		<guid isPermaLink="false">http://www.allfreetech.com/?p=136</guid>
		<description><![CDATA[In this two-part article by Francesco Marchioni, we will be developing and configuring web applications using JBoss web container. Most developers have surely gained some experience with web applications. Therefore, we will not cover the basics of web applications; we will rather disclose how easy it can be to create a consistent web layer for [...]]]></description>
			<content:encoded><![CDATA[<p>In this two-part article by <b>Francesco Marchioni</b>, we will be developing and configuring web applications using JBoss web container. Most developers have surely gained some experience with web applications. Therefore, we will not cover the basics of web applications; we will rather disclose how easy it can be to create a consistent web layer for your applications, using just the right tools and, of course, the right technique.<span id="more-136"></span></p>
<p>We will cover the following topics in more detail:</p>
<ul>
<li>What is JSF and how to install it on JBoss AS</li>
<li>How to create a JSF facade for our pasture application</li>
<li>How to configure JBoss Web Server</li>
</ul>
<p style="margin-left: 40px; margin-right: 40px;">Wonder what was the first message sent through Internet? At 22:30 hours on October 29, 1969, a message was transmitted using ARPANET (the predecessor of the global Internet) on a host-to-host connection. It was meant to transmit &quot;login&quot;. However, it transmitted just &quot;lo&quot; and crashed.</p>
<h1>Developing web layout</h1>
<p>The basic component of any Java web application is the servlet. Born in the middle of the 90s, servlets quickly gained success against their competitors, the CGI scripts. This was because of some innovative features, especially the ability to execute requests concurrently, without the overhead of creating a new process for each request. However, a few things were missing, for example, the <b>servlet API</b> did not address any APIs specifically for creating the client GUI. This resulted in multiple ways of creating the presentation tier, generally with tag libraries that differed from job to job and from individual developers.</p>
<p>The second thing that was missing in the servlet specification was a clear distinction between the presentation tier and the backend. A plethora of web frameworks tried to fill this gap; particularly the <b>Struts</b> framework effectively realized a clean separation of the <b>model</b> (application logic that interacts with a database) from the <b>view</b> (HTML pages presented to the client) and the <b>controller</b> (instance that passes information between view and model).</p>
<p>However, the limitation of these frameworks was that even if they realized a complete modular abstraction, they still failed as they always exposed the<i>HttpServletRequest</i> and <i>HttpServletSession</i>objects to their action(s). Their actions, in turn, needed to accept the interface contracts such as <i>ActionForm</i>,<i> ActionMapping</i>, and so on.</p>
<p>The JavaServer Faces that emerged on the stage a few years later pursued a different approach. Unlike request-driven <b>Model&ndash;View&ndash;Controller (MVC)</b> web frameworks, JSF chose a component-based approach that ties the user interface component to a well-defined request processing lifecycle. This greatly simplifies the development of web applications.</p>
<p>The JSF specification allows you to have presentation components be POJOs. This creates a cleaner separation from the servlet layer and makes it easier to do testing by not requiring the POJOs to be dependent on the servlet classes.</p>
<p>In the following sections, we will describe how to create a web layout for our application store using the JSF technology. For an exhaustive explanation of the JSF framework, we suggest you to surf the JSF homepage at <a href="http://java.sun.com/javaee/javaserverfaces/" target="_blank">http://java.sun.com/javaee/javaserverfaces/</a>.</p>
<h2>Installing JSF on JBoss AS</h2>
<p>JBoss AS already ships with the JSF libraries, so the good news is that you don&#39;t need to download or install them in the application server. There are different implementations of the JSF libraries. Earlier JBoss releases adopted the <b>Apache MyFaces</b> library. JBoss AS 4.2 and 5.x ship with the <b>Common Development and Distribution License</b> (<b>CDDL</b>) implementation (now called &quot;Project Mojarra&quot;) of the JSF 1.2 specification that is available from the java.net open source community.</p>
<p style="margin-left: 40px; margin-right: 40px;"><em>Switching to another JSF implementation is anyway possible. All you have to do is package your JSF libraries with your web application and configure your <i>web.xml</i> to ignore the JBoss built-in implementation:</em></p>
<pre style="margin-left: 40px;">&lt;context-param&gt;
&lt;param-name&gt;org.jboss.jbossfaces.WAR_BUNDLES_JSF_
IMPL&lt;/param-name&gt;
&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p>We will start by creating a new JSF project. From the <b>File</b> menu, select <b>New</b> | <b>Other</b> | <b>JBoss Tools Web</b> | <b>JSF</b> | <b>JSF Web project</b>. The JSF applet wizard will display, requesting the <b>Project Name</b>, the <b>JSF Environment</b>, and the default starting <b>Template</b>.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image01.png" /></p>
<p>Choose <b>AppStoreWeb</b> as the project name, and check that the <b>JSF Environment</b> used is <b>JSF 1.2</b>. You can leave all other options to the defaults and click <b>Finish</b>. Eclipse will now suggest that you switch to the <b>Web Projects</b> view that logically assembles all JSF components. (It seems that the current release of the plugin doesn&#39;t understand your choice, so you have to manually click on the <b>Web Projects</b> tab.)</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image02.png" /></p>
<p>The key configuration file of a JSF application is faces-config.xml contained in the Configuration folder. Here you declare all <b>navigation rules</b> of the application and the <b>JSF managed beans</b>. Managed beans are simple POJOs that provide the logic for initializing and controlling JSF components, and for managing data across page requests, user sessions, or the application as a whole.</p>
<p>Adding JSF functionalities also requires adding some information to your <i>web.xml</i> file so that all requests ending with a certain suffix are intercepted by the <i>Faces Servlet</i>. Let&#39;s have a look at the <i>web.xml</i> configuration file:</p>
<pre style="margin-left: 40px;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;

&lt;display-name&gt;AppStoreWeb&lt;/display-name&gt;
&lt;context-param&gt;
&lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt;
&lt;param-value&gt;server&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt; [1]
&lt;param-name&gt;com.sun.faces.
enableRestoreView11Compatibility&lt;/param-name&gt;
&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;listener&gt;
&lt;listener-class&gt;com.sun.faces.config.
ConfigureListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;!-- Faces Servlet --&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
&lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;!-- Faces Servlet Mapping --&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.jsf&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;login-config&gt;
&lt;auth-method&gt;BASIC&lt;/auth-method&gt;
&lt;/login-config&gt;
&lt;/web-app&gt;
</pre>
<p style="margin-left: 40px; margin-right: 40px;"><em>The context-param pointed out here <b>[1]</b> is not added by default when you create a JSF application. However, it needs to be added, else you&#39;ll stumble into an annoying ViewExpiredException when your session expires (JSF 1.2).</em></p>
<h2>Setting up navigation rules</h2>
<p>In the first step, we will define the navigation rules for our AppStore. A minimalist approach would require a homepage that displays the orders, along with two additional pages for inserting new customers and new orders respectively.</p>
<p>Let&#39;s add the following navigation rule to the <i>faces-config.xml</i>:</p>
<pre style="margin-left: 40px;">&lt;faces-config&gt;
&lt;navigation-rule&gt;
&lt;from-view-id&gt;/home.jsp&lt;/from-view-id&gt; [1]
&lt;navigation-case&gt;
&lt;from-outcome&gt;newCustomer&lt;/from-outcome&gt; [2]
&lt;to-view-id&gt;/newCustomer.jsp&lt;/to-view-id&gt;
&lt;/navigation-case&gt;
&lt;navigation-case&gt;
&lt;from-outcome&gt;newOrder&lt;/from-outcome&gt; [3]
&lt;to-view-id&gt;/newOrder.jsp&lt;/to-view-id&gt;
&lt;/navigation-case&gt;
&lt;/navigation-rule&gt;
&lt;navigation-rule&gt;
&lt;from-view-id&gt;&lt;/from-view-id&gt; [4]
&lt;navigation-case&gt;
&lt;from-outcome&gt;home&lt;/from-outcome&gt;
&lt;to-view-id&gt;/home.jsp&lt;/to-view-id&gt;
&lt;/navigation-case&gt;
&lt;/navigation-rule&gt;
&lt;/faces-config&gt;
</pre>
<p>In a navigation rule, you can have one <i>from-view-id</i> that is the (optional) starting page, and one or more landing pages that are tagged as <i>to-view-id</i>. The <i>from-outcome</i> determines the navigation flow. Think about this parameter as a Struts forward, that is, instead of embedding the landing page in the JSP/servlet, you&#39;ll simply declare a virtual path in your JSF beans.</p>
<p>Therefore, our starting page will be <i>home.jsp</i> <b>[1]</b> that has two possible links&mdash;the <i>newCustomer.jsp</i> form <b>[2]</b> and the <i>newOrder.jsp</i> form <b>[3]</b>. At the bottom, there is a navigation rule that is valid across all pages <b>[4]</b>. Every page requesting the home outcome will be redirected to the homepage of the application.</p>
<p>The above JSP will be created in a minute, so don&#39;t worry if Eclipse validator complains about the missing pages. This configuration can also be examined from the <b>Diagram</b> tab of your <i>faces-config.xml</i>:</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image03.png" /></p>
<p>The next piece of code that we will add to the confi guration is the JSF managed bean declaration. You need to declare each bean here that will be referenced by JSF pages. Add the following code snippet at the top of your <i>faces-config.xml</i> (just before navigation rules):</p>
<pre style="margin-left: 40px;">&lt;managed-bean&gt;
&lt;managed-bean-name&gt;manager&lt;/managed-bean-name&gt; [1]
&lt;managed-bean-class&gt;
com.packpub.web.StoreManagerJSFBean
&lt;/managed-bean-class&gt; [2]
&lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt; [3]
&lt;/managed-bean&gt;
</pre>
<p>The <i>&lt;managed-bean-name&gt;</i> <b>[1]</b> element will be used by your JSF page to reference your beans. The <i>&lt;managed-bean-class&gt;</i> <b>[2]</b> is obviously the corresponding class. The managed beans can then be stored within the request, session, or application scopes, depending on the value of the <i>&lt;managed-bean-scope&gt;</i> element <b>[3]</b>.</p>
<h2>Adding a JSF managed bean</h2>
<p>The <i>StoreManagerJSFBean</i> class follows the JavaBean patterns, providing get and <i>set</i> methods for its properties (to make the code more maintainable, we have skipped the <i>getter</i>/<i>setter</i> methods that simply wrap the fields of the class). We have declared the bean as request bound, so for each user of the application, JSF creates a <i>StoreManagerJSFBean</i> instance, which is stored within the <i>request</i> scope.</p>
<p>Add to your project a new Java class and name it <i>com.packtpub.web.StoreManagerJSFBean</i>:</p>
<pre style="margin-left: 40px;">package com.packpub.web;
// skipping imports
public class StoreManagerJSFBean {
@EJB(mappedName = &quot;AppStoreEJB/local&quot;) [1]
private StoreManager storeManager;
private int customerId;
private int orderQuantity;
private int orderPrice;
private String customerName;
private String customerCountry;
private String orderProduct;
List&lt;Order&gt; listOrders;
List &lt;SelectItem&gt; listCustomers;
public List&lt;SelectItem&gt; getListCustomers() {
if (listCustomers == null) {
listCustomers= new ArrayList();
findAllCustomers();
}
return listCustomers;
}
/*
other getter/setter methods omitted for brevity
*/
public StoreManagerJSFBean() { }
public void findOrders() { [2]
listOrders = storeManager.findAllItems(this.customerId);
}
public void findAllCustomers() {
List&lt;Customer&gt; listCustomersEJB =
storeManager.findAllCustomers();
for(Customer customer:listCustomersEJB) {
listCustomers.add(new
SelectItem(customer.getId(),customer.getName()));
}
}
}
public void saveOrder() {
storeManager.saveOrder(customerId,this.orderPrice,
this.orderQuantity,this.orderProduct);
FacesMessage fm = new FacesMessage(&quot;Saved order for
&quot;+this.orderQuantity+ &quot; of &quot;+this.orderProduct);
FacesContext.getCurrentInstance().addMessage(&quot;Message&quot;, fm);
this.orderPrice=0;
this.orderQuantity=0;
this.orderProduct=null;
}
public void insertCustomer() {
storeManager.createCustomer(this.customerCountry,
this.customerName);
FacesMessage fm = new FacesMessage(&laquo;Created Customer
&laquo;+this.customerName+ &laquo; fromf &laquo;+this.customerCountry);
FacesContext.getCurrentInstance().addMessage(&quot;Message&quot;, fm);
this.customerName=null;
this.customerCountry=null;
// Forces customer reloading
this.listCustomers=null;
}
/* Navigation rules */
public String home() { [4]
return &quot;home&quot;;
}
public String newOrder() {
return &quot;newOrder&quot;;
}
public String newCustomer() {
return &quot;newCustomer&quot;;
}
}
</pre>
<p>As you can see, the <i>StoreManagerJSFBean</i> references the session bean we have created previously (<i>StoreManager</i>). Therefore, we must tell the compiler how to solve this dependency. This can be easily solved by choosing <b>Properties</b> on the current project, and then choosing Projects from the <b>Java Build Path</b> option. Add the project <b>AppStore</b> to your build path, as shown here:</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image04.png" /></p>
<p>Having fixed the compilation issues, we can now concentrate on the JSF bean. The first thing we want to capture your attention to is how the <i>StoreManager</i> EJB is injected <b>[1]</b> in the class, skipping completely the lookup/casting/exception handling part.</p>
<p>The <i>findOrders()</i> method <b>[2]</b> retrieves the list of orders from the <i>StoreManager</i> EJB. They will be displayed later in the <i>dataTable </i>component.</p>
<p>The <i>findAllCustomers()</i> <b>[3]</b> is slightly different. It recalls our entity bean&#39;s corresponding <i>findAllCustomers()</i> method and then populates a <i>SelectItem</i> object with the list of customers. <i>SelectItem</i> is a JSF object used to render a combobox programmatically. In our case, we will populate it with the <i>customerId</i> (as value) and <i>customerName</i> (as label).</p>
<p>The remaining EJB wrapper methods, <i>saveOrder()</i> and <i>insertCustomer()</i>, are quite intuitive; their job is to persist data for <i>Orders</i> and <i>Customers</i>.</p>
<p>The final piece of code is about navigation rules <b>[4]</b> that are coded as simple Java methods returning the outcome view as a string. For example, in order to return to the homepage from any other page, we will add the following button:</p>
<pre style="margin-left: 40px;">&lt;h:commandButton action=&quot;#{manager.home}&quot; value=&quot;Back&quot; /&gt;
</pre>
<h2>Setting up the view</h2>
<p>Setting up the view JSF pages are just behind-the-scenes JSP pages that are engineered by the JSF servlet. Therefore, in order to create your views, add the following pages to your web application: <i>home.jsp</i>, <i>newCustomer.jsp</i> and <i>newOrder.jsp</i>. A new JSP page can be added from the <b>Web Projects</b> menu by right-clicking on the <i>WebContent</i> folder, then choosing <b>New</b> | <b>File</b> | <b>JSP Page</b> and naming it <i>home.jsp</i>.</p>
<pre style="margin-left: 40px;">&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/html&quot; prefix=&quot;h&quot;%&gt; [1]
&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/core&quot; prefix=&quot;f&quot;%&gt;
&lt;html&gt;
&lt;body&gt;
&lt;f:view&gt; [2]
&lt;style type=&quot;text/css&quot;&gt; [3]
@import url(&quot;css/appstore.css&quot;);
&lt;/style&gt;
&lt;h:panelGrid columns=&quot;1&quot; border=&quot;1&quot; styleClass=&quot;spring&quot;&gt; [4]
&lt;f:facet name=&quot;header&quot;&gt;
&lt;h:outputText value=&quot;Order List&quot;/&gt;
&lt;/f:facet&gt;
&lt;h:form id=&quot;listOrdersForm&quot;&gt; [5]
&lt;h:outputText value=&quot;Select Customer:&quot; /&gt; [6]
&lt;h:selectOneMenu id=&quot;selectCustomer&quot;
value=&quot;#{manager.customerId}&quot; styleClass=&quot;buttons&quot;&gt; [7]
&lt;f:selectItems
value=&quot;#{manager.listCustomers}&quot; /&gt;
&lt;/h:selectOneMenu&gt;
&lt;h:commandButton action=&quot;#{manager.findOrders}&quot;
value=&quot;ListOrders&quot; styleClass=&quot;buttons&quot;/&gt; [8]
&lt;h:dataTable value=&quot;#{manager.listOrders}&quot; var=&quot;orders&quot;
border=&quot;1&quot; rowClasses=&quot;row1, row2&quot; headerClass=&quot;header&quot;&gt; [9]
&lt;h:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;h:outputText value=&quot;Product&quot; /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value=&quot;#{orders.product}&quot; /&gt;
&lt;/h:column&gt;
&lt;h:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;h:outputText value=&quot;Price&quot; /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value=&quot;#{orders.price}&quot; /&gt;
&lt;/h:column&gt;
&lt;h:column&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;h:outputText value=&quot;Quantity&quot; /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value=&quot;#{orders.quantity}&quot; /&gt;
&lt;/h:column&gt;
&lt;/h:dataTable&gt;
&lt;h:commandButton action=&quot;#{manager.newCustomer}&quot;
value=&quot;Insert Customer&quot; styleClass=&quot;buttons&quot; /&gt; [10]
&lt;h:commandButton action=&quot;#{manager.newOrder}&quot;
value=&quot;Insert Order&quot; styleClass=&quot;buttons&quot; /&gt; [11]
&lt;/h:form&gt;
&lt;/h:panelGrid&gt;
&lt;/f:view&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>JSF contains two tag libraries <b>[1]</b> called JSF core and HTML Basic. The former provides a few general tags and some other tags that let you register validators and event listeners to UI components. The latter contains JSP tags that render HTML UI components such as buttons, text fields, checkboxes, lists, and so on. The standard prefixes of these two tag libraries are <i>h</i> and <i>f</i>, and they are declared at the beginning of <i>home.jsp</i>.</p>
<p>The <i>view</i> tag <b>[2]</b> is the container for all JavaServer Faces component tags used on a page. <b>Stylesheets [3]</b> are used here to decorate the UI components. The <i>panelGrid</i> <b>[4]</b> component simplifies the task of constructing a layout table, to hold form fields, labels, and buttons. In this case, it will contain the main input form.</p>
<p>The <i>form</i> element <b>[5]</b> manages an HTML form just the same way as standard form HTML. Rendering simple text on the page can be achieved with an <i>outputText </i>tag <b>[6]</b>. Here, you can use value-binding expressions from your JSF beans.</p>
<p>The <i>selectOneMenu</i> element <b>[7]</b> is used to display an HTML combobox that is bound to a bean collection. Review the <i>findAllCustomers()</i> method of your <i>StoreManagerJSFBean</i>, where the combobox is built dynamically.</p>
<p>The <i>commandButton</i> <b>[8]</b> is applied to render an HTML button. In our case, we have bound the button to the <i>findOrders()</i> method of our JSF bean.</p>
<p>A core JSF tag is the <i>dataTable</i> tag <b>[9]</b> that can be used to render an HTML table using a collection from the backing bean. This component is generally used to display tabular data and it offers a vast choice of built-in options for customizing its header and footer, and for paginating the table.</p>
<p>The last two buttons, <b>[10]</b> and <b>[11]</b>, plot the route to the <i>newCustomer</i> and <i>newOrder</i> forms.</p>
<p>The form for inserting a new customer is as follows:</p>
<pre style="margin-left: 40px;">&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/html&quot; prefix=&quot;h&quot;%&gt;
&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/core&quot; prefix=&quot;f&quot;%&gt;
&lt;html&gt;
&lt;body&gt;
&lt;f:view&gt;
&lt;style type=&quot;text/css&quot;&gt;
@import url(&quot;css/appstore.css&quot;);
&lt;/style&gt;
&lt;h:form id=&quot;newCustomer&quot;&gt;
&lt;h:panelGrid columns=&quot;2&quot; border=&quot;1&quot; styleClass=&quot;spring&quot;&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;h:outputText value=&quot;Insert new Customer&quot; /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value=&quot;Name&quot; /&gt;
&lt;h:inputText value=&quot;#{manager.customerName}&quot; /&gt; [1]
&lt;h:outputText value=&quot;Country&quot; /&gt;
&lt;h:inputText value=&quot;#{manager.customerCountry}&quot; /&gt;
&lt;h:commandButton action=&quot;#{manager.insertCustomer}&quot; [2]
value=&quot;Insert Customer&quot; /&gt;
&lt;h:commandButton action=&quot;#{manager.home}&quot; value=&quot;Back&quot; /&gt;
&lt;/h:panelGrid&gt;
&lt;h:messages /&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The <i>inputText</i> fields <b>[1]</b> are used to populate the individual managed bean properties. With the <i>commandButton</i> <b>[2]</b>, the <i>insertCustomer()</i> action is recalled, thus inserting a new customer. This is the last JSP needed for our example <i>newOrder.jsp</i>:</p>
<pre style="margin-left: 40px;">&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/html&quot; prefix=&quot;h&quot;%&gt;
&lt;%@ taglib uri=&quot;http://java.sun.com/jsf/core&quot; prefix=&quot;f&quot;%&gt;
&lt;html&gt;
&lt;body&gt;
&lt;f:view&gt;
&lt;style type=&quot;text/css&quot;&gt;
@import url(&quot;css/appstore.css&quot;);
&lt;/style&gt;
&lt;h:form id=&quot;newOrder&quot;&gt;
&lt;h:panelGrid columns=&quot;2&quot; border=&quot;1&quot; styleClass=&quot;spring&quot;&gt;
&lt;f:facet name=&quot;header&quot;&gt;
&lt;h:outputText value=&quot;Insert new Order&quot; /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value=&quot;Product&quot; /&gt;
&lt;h:inputText value=&quot;#{manager.orderProduct}&quot; /&gt;
&lt;h:outputText value=&quot;Quantity&quot; /&gt;
&lt;h:inputText value=&quot;#{manager.orderQuantity}&quot; /&gt;
&lt;h:outputText value=&quot;Price&quot; /&gt;
&lt;h:inputText value=&quot;#{manager.orderPrice}&quot; /&gt;
&lt;h:outputText value=&quot;Customer&quot; /&gt;
&lt;h:selectOneMenu id=&quot;selectCustomerforOrder&quot;
value=&quot;#{manager.customer}&quot;&gt;
&lt;f:selectItems value=&quot;#{manager.listCustomers}&quot; /&gt;
&lt;/h:selectOneMenu&gt;
&lt;h:commandButton action=&quot;#{manager.saveOrder}&quot;
value=&quot;Save Order&quot; /&gt;
&lt;h:commandButton action=&quot;#{manager.home}&quot; value=&quot;Back&quot; /&gt;
&lt;/h:panelGrid&gt;
&lt;h:messages /&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Assembling and deploying the application</h2>
<p>So far, you have got two standalone projects, one EJB project and one web project. While you could technically deploy them separately, it is worth combining them in an <b>Enterprise ARchive</b> (<b>EAR</b>). The most obvious reason for deploying the application as an Enterprise ARchive is that the web application will be loaded by a <i>ClassLoader</i> in the same hierarchy as the EJB classloader. In short, you don&#39;t need to provide the EJB interfaces to the web application, as you would for a standalone application.</p>
<p>Packaging the application can be done entirely by Eclipse, without messing with archive files. From the menu, select <b>New</b> | <b>Other</b> | <b>Java EE</b> | <b>Enterprise Application project</b>. The next facet will request the <b>Project name</b> and a few details about the configuration. Your archive name will be, by default, the project name plus the extension <i>.ear</i>. Verify that both <b>Target Runtime</b> and the <b>Configuration</b> point correctly to the JBoss 5.0 environment.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image05.png" /></p>
<p>Click <b>Next</b>. On the window that follows, you can select the components of your archive application, that is, the <b>AppStore</b> application and the <b>AppStoreWeb</b> component. Check the option <b>Generate Deployment Descriptor</b>.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image06.png" /></p>
<p>Verify that <i>META-INF/application.xml</i> deployment descriptors contain both the modules enlisted below:</p>
<pre style="margin-left: 40px;">&lt;application&gt;
&lt;display-name&gt;EnterpriseStore&lt;/display-name&gt;
&lt;module&gt;
&lt;web&gt;
&lt;web-uri&gt;AppStoreWeb.war&lt;/web-uri&gt;
&lt;context-root&gt;AppStoreWeb&lt;/context-root&gt;
&lt;/web&gt;
&lt;/module&gt;
&lt;module&gt;
&lt;ejb&gt;AppStore.jar&lt;/ejb&gt;
&lt;/module&gt;
&lt;/application&gt;
</pre>
<p>Okay, now you need only a few more laps to complete the race. Let&#39;s deploy the process to JBoss by switching on the <b>JBoss Server View</b>. Right-click on the JBoss server and select <b>Add and remove projects</b>. Add the <b>EnterpriseStore</b> to the configured projects.</p>
<p>Now deploy the application in the usual way. Right-click on the <b>EnterpriseStore</b> and select <b>Full Publish</b> (at the time of writing, JBoss 5 doesn&#39;t support partial deployment of this component).</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image07.png" /></p>
<p>Verify from the console that the application has been deployed correctly.</p>
<h3>Running the store</h3>
<p>The application gateway will be <i>home.jsf</i> page. Point the browser to the location <i>http://localhost:8080/AppStoreWeb/home.jsf</i>.</p>
<p>Testing the application is quite simple. First add some customers and then link some orders to the customers. In the <i>home.jsf</i> page, check that the orders are correctly listed from the datagrid.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article1-image08.png" /></p>
<p style="margin-left: 40px; margin-right: 40px;"><em><b>A last trick</b><br />
	Usually web applications ship with a <b>welcome file list</b> so that you don&#39;t have to remember anything else besides the web context. If you have already tried to add home.jsf to the welcome file list (in web.xml), you would have noticed that it doesn&#39;t work. Actually, Tomcat is a bit stubborn and requires a trick to set a JSF page as a welcome file. First, add the following to your web.xml:</em></p>
<pre style="margin-left: 40px;">&lt;welcome-file-list&gt;
&lt;welcome-file&gt;home.jsf&lt;/welcome-file&gt;
&lt;/welcome-file-list&gt;
</pre>
<p style="margin-left: 40px; margin-right: 40px;"><em>Then create an empty <i>home.jsf</i> page in your web context root. This will trick Tomcat to detect <i>home.jsf</i> as the welcome file and will load <i>home.jsp</i> instead.</em></p>
<h1>Summary</h1>
<p>This two-part article on creating a web application is about developing and configuring web applications on JBoss AS 5.0 using the JSF cutting-edge technology. In this part of the article we have enhanced the Appstore Enterpirse application by adding a web layer to it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.allfreetech.com/java/creating-a-web-application-on-jboss-as-5-136.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with Ajax Table Editors and Viewers</title>
		<link>http://www.allfreetech.com/ajax/working-with-ajax-table-editors-and-viewers-122.html</link>
		<comments>http://www.allfreetech.com/ajax/working-with-ajax-table-editors-and-viewers-122.html#comments</comments>
		<pubDate>Sun, 17 Jan 2010 07:42:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.allfreetech.com/?p=122</guid>
		<description><![CDATA[A typical Web application shows information that is retrieved from databases and other sources such as data feeds. In many cases, one or more Web forms let the user enter new information or modify the existing data. When the user clicks a button, the form&#39;s data is sent to the server where it is validated [...]]]></description>
			<content:encoded><![CDATA[<p>A typical Web application shows information that is retrieved from databases and other sources such as data feeds. In many cases, one or more Web forms let the user enter new information or modify the existing data. When the user clicks a button, the form&#39;s data is sent to the server where it is validated and processed. Then, the server returns the same form or another page to the user. This application model can be optimized with the help of Ajax, minimizing the network traffic and significantly improving the user&#39;s experience.<span id="more-122"></span></p>
<p>An Ajax client responds much faster to the user&#39;s actions and can provide desktop-like features, increasing user productivity. Instead of regenerating the HTML markup for every request on the server side, the user interface (UI) is loaded once in the browser and then the Ajax client retrieves only the data that it needs, updating the user interface dynamically. In addition, many data requests are sent asynchronously, meaning that they don&#39;t block the UI.</p>
<p>In this article, I&#39;ll show you how to build a Web-based table editor that allows the user to insert/delete rows and undo changes without waiting for a server response and without losing the scroll position. The table component will also act as a viewer that uses Ajax to retrieve information from a data feed. You&#39;ll learn how to use JavaScript to build a table model, create the table editor/viewer, validate data with regular expressions, access the data feed, use event handlers, and monitor the data changes in the Web browser. In addition, I&#39;ll present a very interesting technique for generating XML and HTML on the client side, using a JSP-like syntax that makes the code more readable and easier to maintain.</p>
<h2>Application Overview</h2>
<p>The sample application of this article is a portfolio editor/viewer:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f1.jpg" /></p>
<p>The user enters the stock information and is able to undo the data changes at any moment. The share prices are retrieved from a data feed so that the stock values and their gains/losses can be updated every second. When the user saves the data, the table component is switched to a read-only mode:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f2.jpg" /></p>
<p>I have already presented half of the application&#39;s code in a previous OTN article titled &quot;<a class="bodylink" href="http://www.oracle.com/technology/pub/articles/cioroianu-ajax-data.html">Enabling Data Exchange in Ajax Applications</a>,&quot; and the Ajax utility functions (contained in the ajaxUtil.js file) are reused from another OTN article of mine titled &quot;<a class="bodylink" href="http://www.oracle.com/technology/pub/articles/cioroianu_jsfajax.html">Developing Smart Web UIs with Ajax, JSF, and ADF Faces</a>.&quot; The following table specifies the article that describes each source file and the directory where you can find the file:</p>
<table align="center" border="1" cellpadding="4" cellspacing="0" class="bodycopy" width="600">
<tbody>
<tr bgcolor="#eeeeee">
<td valign="top" width="17%">
<p><strong>Article</strong></p>
</td>
<td valign="top" width="28%">
<p><strong>Directory</strong></p>
</td>
<td valign="top" width="20%">
<p><strong>File</strong></p>
</td>
<td valign="top" width="35%">
<p><strong>Description</strong></p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>src/ajaxapp/util</p>
</td>
<td valign="top">
<p>JSONEncoder.java</p>
</td>
<td valign="top">
<p>JSON encoding utilities</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>src/ajaxapp/util</p>
</td>
<td valign="top">
<p>XMLUtil.java</p>
</td>
<td valign="top">
<p>Schema, DOM, XPath utilities</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>src/ajaxapp/model</p>
</td>
<td valign="top">
<p>DataModel.java</p>
</td>
<td valign="top">
<p>Server-side data model</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>src/ajaxapp/model</p>
</td>
<td valign="top">
<p>StockBean.java</p>
</td>
<td valign="top">
<p>JavaBean used by the data model</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>src/ajaxapp/model</p>
</td>
<td valign="top">
<p>portfolio.xsd</p>
</td>
<td valign="top">
<p>XML Schema file for validation</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>src/ajaxapp/feed</p>
</td>
<td valign="top">
<p>DataFeed.java</p>
</td>
<td valign="top">
<p>Data feed implementation</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>src/ajaxapp/feed</p>
</td>
<td valign="top">
<p>ShareBean.java</p>
</td>
<td valign="top">
<p>JavaBean used by the data feed</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>src/ajaxapp/builder</p>
</td>
<td valign="top">
<p>JSBuilder.java</p>
</td>
<td valign="top">
<p>JavaScript code generator</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>index.jsp</p>
</td>
<td valign="top">
<p>Main page of the portfolio app</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>ajaxCtrl.jsp</p>
</td>
<td valign="top">
<p>Controller for the Ajax requests</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Smart Web UIs</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>ajaxUtil.js</p>
</td>
<td valign="top">
<p>General Ajax utilities</p>
</td>
</tr>
<tr>
<td valign="top">
<p>Data exchange</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>ajaxLogic.js</p>
</td>
<td valign="top">
<p>App-specific Ajax utilities</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>dataModel.js</p>
</td>
<td valign="top">
<p>Client-side data model</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>dataTable.js</p>
</td>
<td valign="top">
<p>UI utilities and event handlers</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html</p>
</td>
<td valign="top">
<p>style.css</p>
</td>
<td valign="top">
<p>Cascading Style Sheet</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html/WEB-INF</p>
</td>
<td valign="top">
<p>feed.tld</p>
</td>
<td valign="top">
<p>Tag Library Descriptor</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html/WEB-INF</p>
</td>
<td valign="top">
<p>web.xml</p>
</td>
<td valign="top">
<p>Web Application Descriptor</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html/WEB-INF/tags</p>
</td>
<td valign="top">
<p>setHeader.tag</p>
</td>
<td valign="top">
<p>Tag that sets an HTTP header</p>
</td>
</tr>
<tr>
<td valign="top">
<p>This article</p>
</td>
<td valign="top">
<p>public_html/WEB-INF/tags</p>
</td>
<td valign="top">
<p>template.tag</p>
</td>
<td valign="top">
<p>Tag that invokes the JSBuilder</p>
</td>
</tr>
</tbody>
</table>
<h1>Data Models and Data Feeds</h1>
<p>Like any typical Web application, the portfolio sample has a server-side data model, which was described in <a class="bodylink" href="http://www.oracle.com/technology/pub/articles/cioroianu-ajax-data.html">&quot;Enabling Data Exchange in Ajax Applications.&quot;</a> The DataModel class can be initialized from an XML document, and its state can be encoded as a JSON string that is used to initialize the client-side data model, which is presented in this section.</p>
<h2>Building Table Models</h2>
<p>The portfolio application uses a JavaScript table model that maintains the user data and the information retrieved from the data feed with Ajax. To create the JavaScript file, open JDeveloper, select an existing project or create a new one, click <strong>File / New</strong>, expand <strong>Web Tier</strong> in the New Gallery window, select the HTML category in the left panel, select <strong>JavaScript File</strong> in the right panel and click <strong>OK</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f3.jpg" /></p>
<p>Enter the dataModel.js file name and click <strong>OK</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f4.jpg" /></p>
<p>The dataModel.js file of the sample application creates an object whose methods are similar to those defined by Swing&#39;s TableModel interface: getRowCount(), getColumnCount(), getColumnName(), getValueAt(), and setValueAt(). Here is the code that creates the data model object:</p>
<pre>var dataModel = {

    columns: [ &quot;Symbol&quot;, &quot;Shares&quot;, &quot;Paid Price&quot;,
        &quot;Last Price&quot;, &quot;Stock Value&quot;, &quot;Gain/Loss&quot; ],

    stocks: [ ],

    getRowCount: function() {
        return this.stocks.length;
    },

    getColumnCount: function() {
        return this.columns.length;
    },

    getColumnName: function(index) {
        return this.columns[index];
    },

    getValueAt: function(row, column) {
        ...
    },

    setValueAt: function(value, row, column) {
        ...
    },

    ...
}
</pre>
<p>The data model object has additional methods that return a stock&#39;s value and gain, calculate the portfolio&#39;s value and gain, get/set all stocks, insert a new stock, and delete an existing stock. You can find the code of these simple methods in the dataModel.js file.</p>
<p>The JavaScript editor of JDeveloper has many useful features such as syntax highlighting and verification, completion and parameter insight, refactoring, usage finding, brace matching, and code folding. In addition, you can use the Structure Navigator to locate declarations and functions:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f5.jpg" /></p>
<p>The JDeveloper release used here (Oracle JDeveloper 11<em>g</em> Technology Preview 2) also includes a JavaScript debugger for Firefox. To view or change the debugger settings, click <strong>Tools / Project</strong> Properties, select <strong>Run/Debug/Profile</strong> in the left panel, choose the <strong>Default</strong> profile in the right panel, and click <strong>Edit</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f6.jpg" /></p>
<p>In the Edit Run Configuration window, select <strong>Launch Settings / JavaScript</strong> in the left panel so that you can setup the debugger:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f7.jpg" /></p>
<h2>Implementing Data Feeds</h2>
<p>A data feed usually provides a Web service or an HTTP-based protocol so that it can be accessed over a network. An Ajax client, however, cannot directly connect to third-party Web services due to security restrictions imposed by the Web browser. Therefore, you need an Ajax controller running on the same server that hosts the Ajax application. This controller should connect to the third-party Web service to retrieve the data for the Ajax client. In order to keep things simple and focus on the Ajax topics, the sample application simulates the data feed, generating random share prices in the ShareBean class:</p>
<pre>package ajaxapp.feed;

public class ShareBean implements java.io.Serializable {
    private String symbol;
    private int trend;
    private double lastPrice;

    public ShareBean(String symbol) {
        this.symbol = symbol;
        trend = 1;
        lastPrice = Math.random() * 100;
    }

    public String getSymbol() {
        return symbol;
    }

    public int getTrend() {
        return trend;
    }

    public double getLastPrice() {
        lastPrice += trend * Math.random() * 0.1;
        if (Math.random() &lt; 0.2)
            trend = -trend;
        return lastPrice;
    }

}
</pre>
<p>The DataFeed class provides a getData() method that takes an array of symbols and returns the share information encoded in a JSON string:</p>
<pre>package ajaxapp.feed;

import ajaxapp.util.JSONEncoder;

import java.util.*;

public class DataFeed implements java.io.Serializable {
    private HashMap&lt;String, ShareBean&gt; shareMap;

    public DataFeed() {
        shareMap = new HashMap&lt;String, ShareBean&gt;();
    }

    public synchronized String getData(String symbols[]) {
        JSONEncoder json = new JSONEncoder();
        json.startArray();
        for (int i = 0; i &lt; symbols.length; i++) {
            String symbol = symbols[i];
            ShareBean share = shareMap.get(symbol);
            if (share == null) {
                share = new ShareBean(symbol);
                shareMap.put(symbol, share);
            }
            json.startObject();
            json.property(&quot;symbol&quot;, share.getSymbol());
            json.property(&quot;trend&quot;, share.getTrend());
            json.property(&quot;lastPrice&quot;, share.getLastPrice());
            json.endObject();
        }
        json.endArray();
        return json.toString();
    }

    public static String getData(
            DataFeed feed, String symbols[]) {
        return feed.getData(symbols);
    }

}
</pre>
<p>The static getData() method is useful for calling the instance method from a JSP page, using an expression language (EL) function that is defined in feed.tld. To create the TLD file, click <strong>File / New</strong>, select the JSP category from Web Tier in the left panel, select the JSP Tag Library item and click <strong>OK</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f8.jpg" /></p>
<p>Skip the Welcome screen of the wizard and select <strong>Project Based</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f9.jpg" /></p>
<p>Provide the feed short name, enter the /ajaxapp/feed URI and click <strong>Finish</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f10.jpg" /></p>
<p>Then, paste the &lt;function&gt; element shown below:</p>
<pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;taglib ...&gt;

    &lt;tlib-version&gt;1.0&lt;/tlib-version&gt;
    &lt;short-name&gt;feed&lt;/short-name&gt;
    &lt;uri&gt;/ajaxapp/feed&lt;/uri&gt;

    &lt;function&gt;
        &lt;name&gt;getData&lt;/name&gt;
        &lt;function-class&gt;ajaxapp.feed.DataFeed&lt;/function-class&gt;
        &lt;function-signature&gt;
            java.lang.String getData(
                ajaxapp.feed.DataFeed, java.lang.String[])
        &lt;/function-signature&gt;
    &lt;/function&gt;

&lt;/taglib&gt;
</pre>
<p>The application&#39;s Ajax controller (called ajaxCtrl.jsp) uses the getData() EL function to obtain the share prices for the Ajax client. A DataFeed instance is used as an application bean in the ajaxCtrl.jsp file:</p>
<pre>&lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags/&quot; %&gt;
&lt;%@ taglib prefix=&quot;feed&quot; uri=&quot;/WEB-INF/feed.tld&quot; %&gt;

&lt;tags:setHeader name=&quot;Cache-Control&quot; value=&quot;no-cache&quot;/&gt;

&lt;jsp:useBean id=&quot;dataFeed&quot; scope=&quot;application&quot;
	class=&quot;ajaxapp.feed.DataFeed&quot; /&gt;
...
${feed:getData(dataFeed, paramValues.symbol)}
</pre>
<p>It is important to set the no-cache header in order to disable the Web browser&#39;s cache. Here is the code of the setHeader.tag file:</p>
<pre>&lt;%@ attribute name=&quot;name&quot; required=&quot;true&quot; %&gt;
&lt;%@ attribute name=&quot;value&quot; required=&quot;true&quot; %&gt;

&lt;%
    String name = (String) jspContext.getAttribute(&quot;name&quot;);
    String value = (String) jspContext.getAttribute(&quot;value&quot;);
    response.setHeader(name, value);
%&gt;
</pre>
<p>Now that we have implemented a data feed on the server side, let&#39;s see how to access it from the Ajax client.</p>
<h2>Accessing Data Feeds</h2>
<p>The Ajax client sends an HTTP request to the controller, which calls the getData() method and returns the JSON string. The HTTP request must contain the parameters, which are the share symbols in the case of this example. The requestFeedInfo() function (whose code can be found in dataTable.js) gets the symbols from the data model and makes sure that each symbol is included only once, because the portfolio could contain multiple stocks with the same symbol:</p>
<pre>function requestFeedInfo() {
    var symbolSet = new Array();
    for (var i = 0; i &lt; dataModel.stocks.length; i++) {
        var symbol = dataModel.stocks[i].symbol;
        if (isValidSymbol(symbol)) {
            for (var j = 0; j &lt; symbolSet.length; j++)
                if (symbol == symbolSet[j].value)
                    symbol = null;
            if (symbol)
                symbolSet[symbolSet.length] = symbol;
        }
    }
    if (symbolSet.length &gt; 0)
        sendInfoRequest(symbolSet, feedInfoCallback);
}
</pre>
<p>The array of symbols is passed to sendInfoRequest() along with feedInfoCallback, which will be invoked when the data is received from the server. The sendInfoRequest() function aborts the previous HTTP request if it hasn&#39;t been completed, and then it builds the array of HTTP parameters that is passed to sendHttpRequest(), which builds and sends the request to the server, using the Ajax API. The sendHttpRequest() function can be found in the ajaxUtil.js file whose code was discussed in a previous OTN article entitled &quot;<a class="bodylink" href="http://www.oracle.com/technology/pub/articles/cioroianu_jsfajax.html">Developing Smart Web UIs with Ajax, JSF, and ADF Faces</a>.&quot; Here is the code of the sendInfoRequest() function from ajaxLogic.js:</p>
<pre>var ctrlURL = &quot;ajaxCtrl.jsp&quot;;
var feedRequest = null;

function sendInfoRequest(symbols, callback) {
    if (feedRequest)
        abortRequest(feedRequest);
    var params = new Array();
    for (var i = 0; i &lt; symbols.length; i++)
        params[i] = {
            name: &quot;symbol&quot;,
            value: symbols[i]
        };
    feedRequest = sendHttpRequest(
        &quot;GET&quot;, ctrlURL, params, callback);
}
</pre>
<p>The Ajax callback can be found in the dataTable.js file. The feedInfoCallback() function evaluates the JSON response with eval(request.responseText), obtaining an object tree that contains the information retrieved from the data feed. Then, it stores the latest share prices into the data model and calls updateDynamicCells() for updating the UI:</p>
<pre>function feedInfoCallback(request) {
    var feedInfo = eval(request.responseText);
    for (var i = 0; i &lt; dataModel.stocks.length; i++) {
        var symbol = dataModel.stocks[i].symbol;
        dataModel.stocks[i].lastPrice = 0;
        for (var j = 0; j &lt; feedInfo.length; j++)
            if (symbol == feedInfo[j].symbol) {
                var value = feedInfo[j].lastPrice;
                dataModel.stocks[i].lastPrice = value;
            }
    }
    updateDynamicCells();
}
</pre>
<p>Before discussing the UI code, let&#39;s see how you can use JavaScript to generate XML and HTML in the Web browser.</p>
<h1>Generating XML and HTML with JavaScript</h1>
<p>Before JSP, servlets were used to dynamically generate HTML content on the server side. It was difficult to create and maintain the servlet code, because the developer had to manually encode HTML strings within the Java code and each line of markup had to be placed in a println() statement. It was difficult to view the page structure, and it wasn&#39;t possible to use visual tools for designing the pages that were coded as servlets.</p>
<p>Today, servlets are doing very well as the foundation of the JSP technology, which provides a much better way for generating markup on the server side. On the client side, however, JavaScript has no JSP equivalent. Many developers use servlets-like coding techniques to dynamically create HTML content, or they use the DOM API. None of these solutions is easy to use when you have to generate HTML or XML with JavaScript.</p>
<h2>Using a JSP-like Syntax with JavaScript</h2>
<p>It would be much easier to use something like this</p>
<pre>&lt;tag attr=&quot;[%= value %]&quot;&gt; [%= data %] &lt;/tag&gt;</pre>
<p>instead of</p>
<pre>&quot;&lt;tag attr=\&quot;&quot; + escapeXML(value) + &quot;\&quot;&gt;&quot; + escapeXML(data) + &quot;&lt;/tag&gt;&quot;</pre>
<p>You wouldn&#39;t have to escape &quot; with \ anymore, and expressions included within the [%= %] constructs would be automatically escaped, meaning that &amp;, &lt;, &gt;, and &quot; would be replaced with &amp;amp;, &amp;lt;, &amp;gt;, and &amp;quot;, respectively. Sometimes you already have a piece of markup and you don&#39;t want to escape &amp;, &lt;, &gt;, and &quot;. In this case, you could use [%# %] instead of [%= %].</p>
<p>So you can easily view the markup&#39;s structure, the blocks of JavaScript code can be wrapped between [% and %] as in the following example:</p>
<pre>&lt;table class=&quot;tableClass&quot;&gt; [%
    for (var i = 0; i &lt; rowCount; i++) { %]
        &lt;tr class=&quot;[%= getRowClass(i) %]&quot;&gt; [%
            for (var j = 0; j &lt; columnCount; j++) { %]
                &lt;td class=&quot;[%= getCellClass(i, j) %]&quot;&gt;
                    [%# buildCell(i, j) %]
                &lt;/td&gt; [%
            } %]
        &lt;/tr&gt; [%
    } %]
&lt;/table&gt;
</pre>
<p>The above template must be translated into valid JavaScript code on the server side. Here is how this should look:</p>
<pre>var content = &quot;&quot;;
content += &quot;&lt;table class=\&quot;tableClass\&quot;&gt;&quot;;
for (var i = 0; i &lt; rowCount; i++) {
    content += &quot;&lt;tr class=\&quot;&quot;;
    content += escapeXML(getRowClass(i));
    content += &quot;\&quot;&gt;&quot;;
    for (var j = 0; j &lt; columnCount; j++) {
        content += &quot;&lt;td class=\&quot;&quot;;
        content += escapeXML(getCellClass(i, j));
        content += &quot;\&quot;&gt;&quot;;
        content += buildCell(i, j);
        content += &quot;&lt;/td&gt;&quot;;
    }
    content += &quot;&lt;/tr&gt;&quot;;
}
content += &quot;&lt;/table&gt;&quot;;
</pre>
<p>As you can see, the code is much easier to read and maintain when you use the JSP-like syntax. Let&#39;s see how to generate the JavaScript code from the template.</p>
<h2>Creating the Code Generator</h2>
<p>The JSBuilder class (of the ajaxapp.builder package) parses the template and generates the JavaScript code. In addition, the JSONEncoder class (of the ajaxapp.util package) provides the means for encoding the JavaScript strings with the character() and string() methods:</p>
<pre>package ajaxapp.util;

public class JSONEncoder {
    private StringBuilder buf;

    public JSONEncoder() {
        buf = new StringBuilder();
    }

    public void character(char ch) {
        switch (ch) {
            case &#39;\&#39;&#39;:
            case &#39;\&quot;&#39;:
            case &#39;\\&#39;:
                buf.append(&#39;\\&#39;);
                buf.append(ch);
                break;
            ...
            default:
                if (ch &gt;= 32 &amp;&amp; ch &lt; 128)
                    buf.append(ch);
                else {
                    ...
                }
        }
    }

    public void string(String str) {
        int length = str.length();
        for (int i = 0; i &lt; length; i++)
            character(str.charAt(i));
    }

    ...

    public String toString() {
        ...
        return buf.toString();
    }

    public void clear() {
        buf.setLength(0);
    }

}
</pre>
<p>The character() and string() methods of the JSONEncoder class need some modifications so they can be used by the code generator. Therefore the createEncoder() method of JSBuilder uses an inner class that overrides character() to output a JavaScript line when it meets the &#39;\n&#39; character. The string() method will output the last line, which might not end with the new line character.</p>
<pre>package ajaxapp.builder;

import ajaxapp.util.JSONEncoder;

public class JSBuilder {
    ...
    private JSONEncoder json;
    private String varName;
    private boolean isHTML;
    private PrintWriter out;

    public JSBuilder() {
        json = createEncoder();
    }

    private JSONEncoder createEncoder() {
        return new JSONEncoder() {
            private void outputLine() {
                String line = toString();
                out.println(varName + &quot; += \&quot;&quot; + line + &quot;\&quot;;&quot;);
                clear();
            }

            public void character(char ch) {
                super.character(ch);
                if (ch == &#39;\n&#39;)
                    outputLine();
            }

            public void string(String str) {
                super.string(str);
                if (toString().length() &gt; 0)
                    outputLine();
            }
        };
    }
    ...
}
</pre>
<p>The printContent() method uses the customized encoder to generate the JavaScript code that reconstructs a piece of HTML or XML content on the client side:</p>
<pre>public class JSBuilder {
    ...
    private void printContent(String content) {
        json.clear();
        json.string(content);
    }
    ...
}
</pre>
<p>The printExpr() method generates the code that escapes and appends an expression:</p>
<pre>public class JSBuilder {
    ...
    private void printExpr(String expr, boolean escapeXML) {
        if (escapeXML)
            expr = &quot;escapeXML(&quot; + expr + &quot;, &quot; + isHTML + &quot;)&quot;;
        out.println(varName + &quot; += &quot; + expr + &quot;;&quot;);
    }
    ...
}
</pre>
<p>The escapeXML() JavaScript function is included in the ajaxUtil.js file.</p>
<p>The build() method parses the template and generates the JavaScript code:</p>
<pre>public class JSBuilder {
    public static final String CODE_STARTER = &quot;[%&quot;;
    public static final String CODE_ENDER = &quot;%]&quot;;
    public static final char EXPR_STARTER = &#39;=&#39;;
    public static final char INCL_STARTER = &#39;#&#39;;
    ...
    public void build(String template, String varName,
            Writer writer, boolean isHTML) {
        this.varName = varName;
        this.isHTML = isHTML;
        out = new PrintWriter(writer, true);
        out.println(&quot;var &quot; + varName + &quot; = \&quot;\&quot;;&quot;);
        int contentStart = 0;
        int contentEnd = template.indexOf(CODE_STARTER);
        while (contentEnd != -1) {
            String content = template.substring(
                    contentStart, contentEnd);
            printContent(content);
            int codeStart = contentEnd + 2;
            int codeEnd = template.indexOf(CODE_ENDER, codeStart);
            if (codeEnd == -1) {
                codeEnd = template.length();
                template += CODE_ENDER;
            }
            char starter = template.charAt(codeStart);
            if (starter == EXPR_STARTER || starter == INCL_STARTER) {
                codeStart++;
                String expr = template.substring(codeStart, codeEnd);
                printExpr(expr, starter == EXPR_STARTER);
            } else {
                String code = template.substring(codeStart, codeEnd);
                out.println(code);
            }
            contentStart = codeEnd + 2;
            contentEnd = template.indexOf(CODE_STARTER, contentStart);
        }
        String content = template.substring(contentStart);
        printContent(content);
    }

}
</pre>
<p>With fewer than 100 lines of code, we&#39;ve built a template parser / code generator, which significantly improves the readability and maintainability of the JavaScript code that dynamically produces HTML or XML on the client-side.</p>
<h2>Using the Code Generator in JSP Pages</h2>
<p>In order to keep the JSP pages scriptless, the JSBuilder&#39;s build() method can be invoked from a custom tag file (named template.tag), which will generate a JavaScript function that returns the generated content. The function&#39;s header can be provided via an attribute, and the template can be placed between the start tag and the end tag. Here is the syntax of the custom tag:</p>
<pre>&lt;tags:template function=&quot;myTemplate(...)&quot;&gt;
     ... template ...
&lt;/tags:template&gt;
</pre>
<p>To create the tag file, click <strong>File / New</strong>, expand Web Tier in the New Gallery window, select the JSP category in the left panel, select <strong>JSP Tag File</strong> in the right panel, and click <strong>OK</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f11.jpg" /></p>
<p>Enter the template.tag file name and click <strong>OK</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f12.jpg" /></p>
<p>Then, paste the following source code. The &lt;jsp:doBody&gt; action is used in the tag file to obtain the template�s body, which is stored in a JSP variable. Then, the template is passed to the build() method, which generates the JavaScript code that will produce the content on the client side. Here is the code of the template.tag file:</p>
<pre>&lt;%@ attribute name=&quot;function&quot; required=&quot;true&quot; %&gt;
&lt;%@ attribute name=&quot;isHTML&quot; required=&quot;false&quot;
    type=&quot;java.lang.Boolean&quot; %&gt;
&lt;%@ tag import=&quot;ajaxapp.builder.JSBuilder&quot; %&gt;

&lt;script language=&quot;javascript&quot;&gt;

    function ${function} {
        &lt;jsp:doBody var=&quot;templateBody&quot;/&gt;
        &lt;%
            Boolean isHTML
                = (Boolean) jspContext.getAttribute(&quot;isHTML&quot;);
            if (isHTML == null)
                isHTML = new Boolean(false);
            String templateBody
                = (String) jspContext.getAttribute(&quot;templateBody&quot;);
            new JSBuilder().build(templateBody, &quot;content&quot;,
                jspContext.getOut(), isHTML.booleanValue());
        %&gt;
        return content;
    }

&lt;/script&gt;
</pre>
<p>The index.jsp page of the sample application uses the template tag to generate JavaScript functions that produce dynamic HTML content as well as an XML document containing the portfolio�s data. You&#39;ll see later in the article how the HTML pieces are inserted into the Web page with innerHTML. The XML document is sent to the server with XMLHttpRequest.</p>
<p>You can use Oracle JDeveloper to insert the tag into the JSP page. Select Local Tag Files: /WEB-INF/tags/ in the Component Palette. Then, drag <strong>Template</strong> from the palette and drop it on the head tag, which is shown in the Structure Navigator. JDeveloper starts a wizard that lets you enter the required function attribute in the Common Properties tab and the optional isHTML attribute in the Advanced Properties tab. Enter the buildPortfolioDoc() function header, and click <strong>Finish</strong>:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f13.jpg" /></p>
<p>JDeveloper will insert the &lt;tags:template&gt; tag within the &lt;head&gt; element of the JSP page. After that, you may enter the template�s body. Here is the code that generates JavaScript function, which returns the portfolio XML document:</p>
<pre>&lt;tags:template function=&quot;buildPortfolioDoc()&quot;&gt;
    &lt;portfolio&gt; [%
        var stocks = dataModel.stocks;
        for (var i = 0; i &lt; stocks.length; i++) {
            var stock = stocks[i]; %]
            &lt;stock symbol=&quot;[%= stock.symbol %]&quot;
                shares=&quot;[%= stock.shares %]&quot;
                paidPrice=&quot;[%= stock.paidPrice %]&quot;/&gt; [%
        } %]
    &lt;/portfolio&gt;
&lt;/tags:template&gt;
</pre>
<p>The next section shows how to use the custom tag for building the table editor/viewer.</p>
<h1>Table Editors and Viewers</h1>
<p>There are many cases when a table component must change dynamically in response to the user&#39;s actions. For example, a row could be inserted or deleted when the user clicks a button. If the table&#39;s content is recreated on the server, the user must wait while the table is reloaded and the scroll position is lost. If the user has just inserted an empty row, he/she must scroll down to find the new line where data must be entered. This is a time-consuming operation that can be avoided, using Ajax and DHTML.</p>
<h2>Initializing the User Interface</h2>
<p>The application&#39;s main page (index.jsp) declares the used tag libraries, JavaScript files, and style sheet:</p>
<pre>&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;
&lt;%@ taglib prefix=&quot;tags&quot; tagdir=&quot;/WEB-INF/tags/&quot; %&gt;

&lt;html&gt;
&lt;head&gt;

&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; type=&quot;text/css&quot;&gt;

&lt;script src=&quot;ajaxUtil.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;ajaxLogic.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;dataModel.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;dataTable.js&quot;&gt;&lt;/script&gt;

...
&lt;/head&gt;
...
&lt;/html&gt;
</pre>
<p>You can use JDeveloper&#39;s editors and wizards to build JSP pages. To insert a JSP directive or a standard action, select <strong>JSP</strong> in the Component Palette, and then click or drag the desired element:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f14.jpg" /></p>
<p>Click <strong>Taglib Directive</strong> and select a JSP library that you want to use in the Web page:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f15.jpg" /></p>
<p>You can also use JDeveloper to insert HTML tags in a Web page. Select <strong>HTML</strong> in the Component Palette, select the <strong>Common</strong> category, and click <strong>Script</strong>. Then select the JavaScript file whose functions you want to call in the Web page:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f16.jpg" /></p>
<p>The body of the index.jsp page contains two elements (&lt;span&gt; and &lt;div&gt;) whose content will be set later with the help of innerHTML. The onLoad attribute indicates the function that the browser must call after loading the page:</p>
<pre>&lt;body onLoad=&quot;init()&quot;&gt;

&lt;h1 align=&quot;center&quot;&gt;&lt;span id=&quot;title&quot;&gt;&lt;/span&gt;&lt;/h1&gt;

&lt;div id=&quot;dataTable&quot;&gt;
&lt;/div&gt;

&lt;/body&gt;
</pre>
<p>The init() function tries to load the portfolio, using the sendLoadRequest() utility from the ajaxLogic.js file. If the loading succeeds, stocks are stored into the client-side data model and the editing flag is set to false. Otherwise, init() adds three empty rows and sets the editing mode. The requestFeedInfo() function is scheduled with setInterval() to be called every second:</p>
<pre>function init() {
    var stocks = sendLoadRequest();
    if (stocks &amp;&amp; stocks.length &gt; 0) {
        dataModel.setStocks(stocks);
        addDataChange();
        setEditing(false);
    } else {
        for (var i = 0; i &lt; 3; i++)
            dataModel.insertStock(i);
        addDataChange();
        setEditing(true);
    }
    setInterval(&quot;requestFeedInfo()&quot;, 1000);
}
</pre>
<h2>Using Cascading Style Sheets</h2>
<p>The sample application uses the following CSS<strong> </strong>file:</p>
<pre>BODY { background: #FFFFFF; color: #000000; }
TH { font-weight: bold;
     background-color: #EEF8FF;
     border-top: 1px solid #CCCCCC;
     border-right: 1px solid #CCCCCC;
     border-bottom: 1px solid #CCCCCC; }
TD { font-weight: normal;
     background-color: #FFFFFF;
     border-right: 1px solid #CCCCCC;
     border-bottom: 1px solid #CCCCCC; }
TH.symbol, TD.symbol { text-align: left;
     border-left: 1px solid #CCCCCC; }
TH.number, TD.number { text-align: right; }
TD.button { text-align: center; }
TD.leftButton { text-align: center;
     border-left: 1px solid #CCCCCC; }
BUTTON { background-color: #EEEEEE; }
INPUT.valid { background-color: #FFFFFF; }
INPUT.error { background-color: #FFEEEE; }
SPAN.gain { color: #008000; }
SPAN.loss { color: #FF0000; }
A:link, A:visited { color: #000000;
     text-decoration: underline; }
A:hover, A:active { color: #FF0000;
     text-decoration: underline; }
</pre>
<p>You can use Oracle JDeveloper to enter the values of the CSS properties:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f17.jpg" /></p>
<h2>Creating Tables with JavaScript</h2>
<p>The JavaScript code that builds the sample application&#39;s table is generated in the index.jsp file with the custom template tag presented in the previous section. Here is the code for building a single cell of the table:</p>
<pre>&lt;tags:template function=&quot;buildCell(row, column)&quot; isHTML=&quot;true&quot;&gt; [%
    var value = &quot;&quot;;
    if (!isDynamic(row, column))
        value = dataModel.getValueAt(row, column);
    if (isEditable(row, column)) {
        var id = getInputId(row, column); %]
        &lt;input id=&quot;[%= id %]&quot; name=&quot;[%= id %]&quot; value=&quot;[%= value %]&quot;
            type=&quot;text&quot; size=&quot;[%= column == 2 ? 6 : 4 %]&quot;
            onKeyUp=&quot;validateCellData([%= row %], [%= column %])&quot;
            onChange=&quot;dataChanged([%= row %], [%= column %])&quot;&gt; [%
    } else {
        var id = getSpanId(row, column); %]
        &lt;span id=&quot;[%= id %]&quot;&gt;[%= value %]&lt;/span&gt; [%
    } %]
&lt;/tags:template&gt;
</pre>
<p>The dataTable.js file contains the JavaScript functions that are called from the template code. The isDynamic() function returns true if the cell&#39;s value is computed using data that is retrieved from the feed:</p>
<pre>function isDynamic(row, column) {
    return column &gt;= 3;
}
</pre>
<p>The isEditable() function returns true if the user can modify the cell&#39;s value:</p>
<pre>function isEditable(row, column) {
    return isEditing() &amp;&amp; column &lt; 3;
}
</pre>
<p>The getInputId() and getSpanId()<strong> </strong>functions return the IDs of the &lt;input&gt; and &lt;span&gt; elements of the cells:</p>
<pre>function getInputId(row, column) {
    return &quot;input_&quot; + row + &quot;_&quot; + column;
}

function getSpanId(row, column) {
    return &quot;span_&quot; + row + &quot;_&quot; + column;
}
</pre>
<p>The buttons and links are generated with another template. The buildButton() function accepts three parameters: the button&#39;s label, the event handler that must be called when the button (or the link) is clicked, and an optional parameter for the handler function:</p>
<pre>&lt;tags:template function=&quot;buildButton(label, handler, param)&quot;
         isHTML=&quot;true&quot;&gt; [%
    if (!param) param = &quot;&quot;; %]
    &lt;c:if test=&quot;${initParam.useButtons}&quot;&gt;
        &lt;button onClick=&quot;[%# handler %]([%# param %])&quot; type=&quot;button&quot;&gt;
            [%= label %]
        &lt;/button&gt;
    &lt;/c:if&gt;
    &lt;c:if test=&quot;${!initParam.useButtons}&quot;&gt;
        &lt;a href=&quot;javascript:[%# handler %]([%# param %])&quot;&gt;
            [%= label %]
        &lt;/a&gt;
    &lt;/c:if&gt;
&lt;/tags:template&gt;
</pre>
<p>The useButtons parameter, which is configured in the web.xml file, determines whether buildButton() generates a button or a link:</p>
<pre>&lt;web-app ...&gt;

    &lt;context-param&gt;
        &lt;param-name&gt;useButtons&lt;/param-name&gt;
        &lt;param-value&gt;true&lt;/param-value&gt;
    &lt;/context-param&gt;
    ...
&lt;/web-app&gt;
</pre>
<p>The table&#39;s template starts with the header that contains the column names. The buildCell() and buildButton() functions are used to generate the content of the cells. The last row contains additional buttons and the totals:</p>
<pre>&lt;tags:template function=&quot;buildTable()&quot; isHTML=&quot;true&quot;&gt;
    &lt;table border=0 cellpadding=5 cellspacing=0 align=&quot;center&quot;&gt;
        &lt;tr&gt; [%
            var columnCount = dataModel.getColumnCount();
            for (var j = 0; j &lt; columnCount; j++) { %]
                &lt;th class=&quot;[%= j == 0 ? &quot;symbol&quot; : &quot;number&quot; %]&quot;&gt;
                    [%= dataModel.getColumnName(j) %]
                &lt;/th&gt; [%
            }
            if (isEditing()) { %]
                &lt;th class=&quot;header&quot; colspan=&quot;2&quot;&gt;&nbsp;&lt;/th&gt; [%
            } %]
        &lt;/tr&gt; [%
        var rowCount = dataModel.getRowCount();
        for (var i = 0; i &lt; rowCount; i++) { %]
            &lt;tr&gt; [%
                for (var j = 0; j &lt; columnCount; j++) { %]
                    &lt;td class=&quot;[%= j == 0 ? &quot;symbol&quot; : &quot;number&quot; %]&quot;&gt;
                        [%# buildCell(i, j) %]
                    &lt;/td&gt; [%
                }
                if (isEditing()) { %]
                    &lt;td class=&quot;button&quot;&gt;
                        [%# buildButton(&quot;Insert&quot;, &quot;insertAction&quot;, i) %]
                    &lt;/td&gt;
                    &lt;td class=&quot;button&quot;&gt;
                        [%# buildButton(&quot;Delete&quot;, &quot;deleteAction&quot;, i) %]
                    &lt;/td&gt; [%
                } %]
            &lt;/tr&gt; [%
        } %]
        &lt;tr&gt;
            &lt;td class=&quot;leftButton&quot; colspan=&quot;3&quot;&gt; [%
                if (isEditing()) { %]
                    [%# buildButton(&quot;Save&quot;, &quot;saveAction&quot;) %] [%
                } else { %]
                    [%# buildButton(&quot;Edit&quot;, &quot;editAction&quot;) %] [%
                } %]
            &lt;/td&gt;
            &lt;td class=&quot;number&quot;&gt;Total:&lt;/td&gt;
            &lt;td class=&quot;number&quot;&gt;&lt;span id=&quot;totalValue&quot;&gt;&lt;/span&gt;&lt;/td&gt;
            &lt;td class=&quot;number&quot;&gt;&lt;span id=&quot;totalGain&quot;&gt;&lt;/span&gt;&lt;/td&gt; [%
            if (isEditing()) { %]
                &lt;td class=&quot;button&quot;&gt;
                    [%# buildButton(&quot;Add&quot;, &quot;insertAction&quot;, rowCount) %]
                &lt;/td&gt;
                &lt;td class=&quot;button&quot;&gt;
                    [%# buildButton(&quot;Undo&quot;, &quot;undoAction&quot;) %]
                &lt;/td&gt; [%
            } %]
        &lt;/tr&gt;
    &lt;/table&gt;
&lt;/tags:template&gt;
</pre>
<p>The generated buildTable() function is called from updateTableComponent(), whose code can be found in the dataTable.js file:</p>
<pre>function updateTableComponent() {
    getElementById(&quot;dataTable&quot;).innerHTML = buildTable();
    updateDynamicCells();
    requestFeedInfo();
    if (isEditing())
        validateTableData();
}
</pre>
<p>The getElementById() function calls the document&#39;s getElementById(), which returns the DOM object representing the HTML element that has the given ID:</p>
<pre>function getElementById(id) {
    return document.getElementById(id);
}
</pre>
<p>The isEditing() function returns the value of the editing flag, which indicates whether the table component is in editing or viewing mode:</p>
<pre>var editing = false;
...
function isEditing() {
    return editing;
}
</pre>
<p>In addition to setting the editing flag, the setEditing() function modifies the page&#39;s title and updates the table component:</p>
<pre>function setEditing(value) {
    editing = value;
    var title = &quot;AJAX-based Portfolio &quot;
        + (editing ? &quot;Editor&quot; : &quot;Viewer&quot;);
    getElementById(&quot;title&quot;).innerHTML = title;
    updateTableComponent();
}
</pre>
<h2>Validating Table Editor&#39;s Data</h2>
<p>Regular expressions provide an easy way to validate data with JavaScript. For example, a share symbol can be validated with the following function, whose code can be found in dataTable.js:</p>
<pre>function isValidSymbol(symbol) {
    return symbol &amp;&amp; (symbolRE.exec(symbol) == symbol);
}
</pre>
<p>The sample application uses three regular expressions for validating the user input:</p>
<pre>var symbolRE = /[A-Za-z][A-Za-z][A-Za-z][A-Za-z]?/;
var numberRE = /\d+/;
var priceRE = /\d+\.?\d*/;
</pre>
<p>The validateCellData() function validates the value of a single cell:</p>
<pre>function validateCellData(row, column) {
    if (!isEditable(row, column))
        return true;
    var valid = false;
    var inputElem = getElementById(getInputId(row, column));
    var value = inputElem.value;
    if (value) {
        var regexp = null;
        switch (column) {
            case 0: regexp = symbolRE; break;
            case 1: regexp = numberRE; break;
            case 2: regexp = priceRE; break;
        }
        if (regexp != null)
            valid = regexp.exec(value) == value;
    }
    inputElem.className = valid ? &quot;valid&quot; : &quot;error&quot;;
    return valid;
}
</pre>
<p>User errors are signaled with the pink color of the error style:</p>
<p><img alt="" src="http://www.oracle.com/technology/pub/images/cioroianu-ajaxtables-f18.jpg" /></p>
<p>The validateTableData() function verifies the data of the whole table:</p>
<pre>function validateTableData() {
    var allValid = true;
    for (var i = 0; i &lt; dataModel.getRowCount(); i++)
        for (var j = 0; j &lt; dataModel.getColumnCount(); j++) {
            var valid = validateCellData(i, j);
            allValid = allValid &amp;&amp; valid;
        }
    return allValid;
}
</pre>
<p>Data should be revalidated on the server for security reasons. The sample application (<a class="bodylink" href="http://www.oracle.com/technology/pub/files/cioroianu-ajaxtable-sample.zip">download</a>) uses the portfolio.xsd schema for this operation.</p>
<h2>Refreshing Table Viewer&#39;s Data</h2>
<p>In a JavaScript application, data can be formatted using custom utilities, such as the formatPrice() function, which returns a string representation of a numeric price:</p>
<pre>function formatPrice(value) {
    var n = new Number(value);
    if (isNaN(n) || n == 0)
        return &quot;&nbsp;&quot;;
    return n.toFixed(2);
}
</pre>
<p>The updateDynamicCells() function updates all dynamic cells of the table. After locating the &lt;span&gt; element of each dynamic cell, the content is changed, using the innerHTML property of the &lt;span&gt; element. If the cell represents a gain or a loss, its style can be changed too, using the className property of the same &lt;span&gt; element:</p>
<pre>function updateDynamicCells() {
    for (var i = 0; i &lt; dataModel.getRowCount(); i++) {
        for (var j = 0; j &lt; dataModel.getColumnCount(); j++) {
            if (isDynamic(i, j)) {
                var value = dataModel.getValueAt(i, j);
                var spanElem = getElementById(getSpanId(i, j));
                spanElem.innerHTML = formatPrice(value);
                if (j == 5)
                    spanElem.className = value &gt;= 0 ? &quot;gain&quot; : &quot;loss&quot;;
            }
        }
    }
    var totalValue = dataModel.getTotalValue();
    var totalValueElem = getElementById(&quot;totalValue&quot;)
    totalValueElem.innerHTML = formatPrice(totalValue);
    var totalGain = dataModel.getTotalGain();
    var totalGainElem = getElementById(&quot;totalGain&quot;)
    totalGainElem.innerHTML = formatPrice(totalGain);
    totalGainElem.className = totalGain &gt;= 0 ? &quot;gain&quot; : &quot;loss&quot;;
}
</pre>
<h2>Using Event Handlers</h2>
<p>The dataTable.js file contains the code that handles the UI events. Every time the user changes the value of a cell, the browser calls the dataChanged() function, whose call is coded in value of the onChange attribute of each &lt;input&gt; element. The dataChanged() function validates the cell&#39;s data, stores the new value in the data model, updates the dynamic cells, and requests the feed information just in case the user entered a new symbol:</p>
<pre>function dataChanged(row, column) {
    validateCellData(row, column);
    var inputElem = getElementById(getInputId(row, column));
    dataModel.setValueAt(inputElem.value, row, column);
    addDataChange();
    updateDynamicCells();
    requestFeedInfo();
}
</pre>
<p>The addDataChange() function saves the stocks into the dataChanges array:</p>
<pre>var dataChanges = new Array();
...
function addDataChange() {
    dataChanges[dataChanges.length]
        = dataModel.getStocks();
}
</pre>
<p>The undoAction() function is called each time the user clicks the Undo button. The previous stocks are retrieved from the dataChanges array. Then, the data model and the table are updated:</p>
<pre>function undoAction() {
    if (dataChanges.length &gt;= 2) {
        var stocks = dataChanges[dataChanges.length-2];
        dataChanges.length--;
        dataModel.setStocks(stocks);
        updateTableComponent();
    }
}
</pre>
<p>The insertAction() function inserts a new row:</p>
<pre>function insertAction(row) {
    dataModel.insertStock(row);
    addDataChange();
    updateTableComponent();
}
</pre>
<p>The deleteAction() function deletes a row:</p>
<pre>function deleteAction(row) {
    dataModel.deleteStock(row);
    addDataChange();
    updateTableComponent();
}
</pre>
<p>The saveAction() function sends the portfolio&#39;s data to the server, using the buildPortfolioDoc() function that is generated in index.jsp and the sendSaveRequest() function whose code can be found in ajaxLogic.js. The portfolio is saved only if the entire table&#39;s data is valid:</p>
<pre>function saveAction() {
    if (validateTableData()) {
        sendSaveRequest(buildPortfolioDoc());
        setEditing(false);
    } else {
        alert(&quot;Please provide valid values for the pink fields.&quot;);
    }
}
</pre>
<p>The editAction() function just calls setEditing(true):</p>
<pre>function editAction() {
    setEditing(true);
}
</pre>
<h1>Summary</h1>
<p>In this article, you&#39;ve learned how to build Swing-like table models and implement data feeds that are accessed with the help of Ajax. Then, you&#39;ve seen how to use a JSP-like syntax for generating HTML and XML with JavaScript. Finally, you&#39;ve found out how to build table components, validate and format their data with JavaScript, define their appearance with CSS, handle events, and undo the data changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.allfreetech.com/ajax/working-with-ajax-table-editors-and-viewers-122.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Swinging and Tweeting with Java and NetBeans</title>
		<link>http://www.allfreetech.com/java/swinging-and-tweeting-with-java-and-netbeans-129.html</link>
		<comments>http://www.allfreetech.com/java/swinging-and-tweeting-with-java-and-netbeans-129.html#comments</comments>
		<pubDate>Thu, 01 Jan 1970 00:00:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://www.allfreetech.com/?p=129</guid>
		<description><![CDATA[In this article by Alfonso Romero, we will discuss how to go about building a custom application for Twitter using java and NetBeans, instead of using the standard web interace. We will learn how login into Twitter using our application and also see the last tweet. Due to the fact that writing a Java app [...]]]></description>
			<content:encoded><![CDATA[<p>In this article by <b>Alfonso Romero</b>, we will discuss how to go about building a custom application for Twitter using java and NetBeans, instead of using the standard web interace. We will learn how login into Twitter using our application and also see the last tweet.</p>
<p>Due to the fact that writing a Java app to control your Twitter account is quite a long process and requires several features, I intend to divide this article in several sections, so you can see in extreme detail all the bells and whistles involved in writing Java applications.</p>
<h1>Downloading and installing NetBeans for your developing platform</h1>
<p>To download NetBeans, open a web browser window and go to the <a href="http://www.netbeans.org" target="_blank">NetBeans</a> website. Then click on the <span style="font-style: italic;">Download</span> button and select the <span style="font-style: italic;">All IDE download</span> bundle. After downloading NetBeans, install it with the default options.</p>
<h1>Creating your SwingAndTweet project</h1>
<ol>
<li>Open NetBeans and select <b>File </b><b>|</b><b> New Project</b> to open the <b>New Project</b> dialog. Now select <b>Java</b> from the <b>Categories</b> panel and<b> Java Application</b> from the <b>Projects</b> panel. Click on <b>Next</b> to continue.</li>
<li>The <b>New Java Application</b> dialog will show up next. Type <i>SwingAndTweet</i> in the <i>Project Name</i> field, mark the <i>Use Dedicated Folder for Storing Libraries</i> option, deselect the <i>Create Main Class</i> box (we&rsquo;ll deal with that later), make sure the <b>Set as Main Project</b> box is enabled and click on<b> Next</b> to continue:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-1.png" /></p>
</li>
<li>NetBeans will create the <i>SwingAndTweet</i> project and will show it under the <i>Projects</i> tab, in the NetBeans main window. Right click on the project&rsquo;s name and select <i>JFrame Form</i>&#8230; in the pop-up menu:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-2.png" /></p>
</li>
<li>The <b>New JFrame Form</b> window will appear next. Type <i>SwingAndTweetUI</i> in the <i>Class Name</i> field, type <i style="font-weight: bold;">swingandtweet</i> in the <i>Package</i> field and click on <i>Finish</i> to continue:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-3.png" /></p>
</li>
<li>NetBeans will open the <i style="font-weight: bold;">SwingAndTweetUI</i> frame in the center panel of the main screen. Now you&rsquo;re ready to assemble your Tweeter Java application!</li>
<li>Now let me explain a little bit about what we did in the previous exercise: First, we created a new Java application called <span style="font-weight: bold;">SwingAndTweet</span>. Then we created a Swing <b>JFrame</b> component and we named it <i>SwingAndTweetUI</i>, because this is going to act as the foundation, where we&rsquo;re going to put all the other Swing components required to interact with Twitter. Now I&rsquo;m going to show you how to download and integrate the <i>Twitter4J API</i> to your <i>SwingAndTweet</i>Java application.</li>
</ol>
<h1>Downloading and integrating the Twitter4J API into your NetBeans environment</h1>
<p>For us to be able to use the powerful classes and methods from the <i>Twitter4J API</i>, we need to tell NetBeans where to find them and integrate them into our Java applications.</p>
<ol>
<li>Open a web browser window, go to <a href="http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/" target="_blank">http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/</a> and search for the latest <i>twitter4j.2.X.X.jar</i> file, or download the most recent version at the time of this writing from here:<a href="http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/2.0.9/twitter4j-2.0.9.jar" target="_blank">http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/2.0.9/twitter4j-2.0.9.jar.</a></li>
<li>Once you download it in your computer, go to NetBeans, right-click on the <i>SwingAndTweet</i> project and select <i>Properties</i> from the context menu. Once at the project properties screen, select the <i>Libraries</i> category under the <i>Categories</i> panel, click on the <i>Add JAR/Folder</i>&#8230; button at the middle-right part of the screen to open the <i>Add JAR/Folder</i> dialog, navigate to the directory where you downloaded the <i>twitter4j-2.X.X.jar</i> file and double click on it to add it to your project&rsquo;s library path:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-4.png" /></p>
</li>
<li>Click on <span style="font-style: italic;">OK</span> to close the <i>Project Properties </i>dialog and return to the NetBeans main screen.</li>
</ol>
<p>Ok, you have integrated the <i>Twitter4J API</i> to your <i>SwingAndTweet</i> application. Now, let&rsquo;s see how to log into your Twitter account from our Java application&#8230;</p>
<h1>Logging into Twitter from Java and seeing your last Tweet</h1>
<p>In the following exercise, I&rsquo;ll show you how easy it is to start communicating with Twitter from a Java application, thanks to the Twitter class from the Twitter4J API. You&lsquo;ll also learn how to check your last tweet through your Java application.</p>
<p>Let&rsquo;s see how to log into a Twitter account:</p>
<ol>
<li>Go to the <i>Palette</i> window and locate the <i>JLabel</i> component under the <i>Swing Controls</i> section; then drag and drop it into the <i>TweetAndSwing</i> <i>JFrame</i> component:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-5.png" /></p>
</li>
<li>Now drag a <i>Button</i> and a <i>Text Editor</i>, too. Once you have the three controls inside the <i>SwingAndTweetUI JFrame</i> control, arrange them as shown below:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-6.png" /></p>
</li>
<li>The next step is to change their names and captions, to make our application look more professional. Right click on the <i>JLabel1</i> control, select <i>Edit</i> from the context menu, type <i>My Last Tweet</i> and hit <b>Enter</b>. Do the same procedure with the other two controls: erase the text in the <b>jTextField1</b> control and type <i>Login</i> in the <i>jButton1</i> control.</li>
<li>Rearrange the <i>jLabel1</i> and <i>jTextField1</i> controls, and drag one of the ends of <i>jTextField1</i> to increase its length all you can. Once done, your application will look like this:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-7.png" /></p>
</li>
<li>
<ol>
<li value="5">And now, let&rsquo;s inject some life to our application! Double click on the <i>JButton1</i> control to open your application&rsquo;s code window. You&rsquo;ll be inside a java method called <b>jButton1ActionPerformed</b>. This method will execute every time you click on the <i>Login</i> button, and this is where we&rsquo;re going to put all the code for logging into your Twitter account.</li>
<li>Delete the <i>// TODO add your handling code here</i>: line and type the following code inside the <b>JButton1ActionPerformed</b> method:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-8.png" /></p>
<p>
				Remember to replace <i>username</i> and <i>password</i> with your real Twitter username and password.</li>
<li>If you look closely at the line numbers, you&lsquo;ll notice there are five error icons on lines 82, 84, 85,&nbsp; 88 and 89. That&rsquo;s because we need to add some import lines at the beginning of your code, to indicate NetBeans where to find the <i>Twitter</i> and <i>JOptionPane</i> classes, and the <i>TwitterException</i>.</li>
<li>Scroll up until you locate the package swingandtweet; line; then add the following lines:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-9.png" /></p>
</li>
<li>Now all the errors will disappear from your code. To see your Java application in action, press <b>F6</b> or select <i>Run&nbsp; Run </i><i>|</i><i> Main Project</i> from the NetBeans main menu. The Run Project window will pop up, asking you to select the main class for your project. The <i>swingandtweet.SwingAndTweetUI</i> class will already be selected, so just click on <span style="font-style: italic;">OK</span> to continue.</li>
<li>Your <i>SwingAndTweetUI</i> application window will appear next, showing the three controls you created. Click on the<span style="font-style: italic;"> Login</span> button and wait for the <i>SwingAndTweet</i> application to validate your Twitter username and password. If they&rsquo;re correct, the following dialog will pop up:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-10.png" /></p>
</li>
<li>Click on <b>OK</b> to return to your <i>SwingAndTweet</i> application. Now you will see your last tweet on the textbox control:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-11.png" /></p>
</li>
<li>If you want to be really sure it&rsquo;s working, go to your Twitter account and update your status through the Web interface; for example, type <i>Testing my Java app</i>. Then return to your <i>SwingAndTweet</i> application and click on the <i>Login</i> button again to see your last tweet. The textbox control will now reflect your latest tweet:
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/java-netbeans-12.png" /></p>
</li>
<li>As you can see, your <i>SwingAndTweet</i> Java application can now communicate with your Twitter account! Click on the<i> <span style="font-weight: bold;">X</span></i><span style="font-weight: bold;"> </span>button to close the window and exit your <i>SwingAndTweet</i> application.</li>
</ol>
<h1>Examining the code</h1>
<p>Ok, I know this is a very simple example, but nevertheless we need to look at the code you wrote, because it will be the clue to add more features to your new Java app, like seeing your followers, the people you follow, the latest tweets from you and the people you follow, and what&rsquo;s more important, you&rsquo;ll be able to update your status without having to log into the Web interface anymore!</p>
<p>And know let&rsquo;s talk about the code. Below you&rsquo;ll find the complete code for the <b>jButton1ActionPerformed</b> method, so you don&rsquo;t have to go back and forth between this article and your code:<span style="font-family: monospace;"><br />
			</span></p>
<pre style="margin-left: 40px;">try {
           Twitter twitter = new Twitter(&quot;alromeromx&quot;, &quot;Nina1976742&quot;);
           twitter.verifyCredentials();
           JOptionPane.showMessageDialog(null, &quot;You&#39;re logged in!&quot;);
           java.util.List&lt;Status&gt; statusList = twitter.getUserTimeline();
           String s = String.valueOf(statusList.get(0).getText());
           jTextField1.setText(s);
        } catch (TwitterException e) {

	JOptionPane.showMessageDialog (null, &quot;Login failed&quot;);

	}
</pre>
<p>The first thing to notice is that all the code is surrounded by a <b>try-catch</b> statement. For those of you who haven&rsquo;t worked with <b>try-catch</b>, just keep in mind that the <b>try</b> block contains the code that will execute until an error shows up; in this case, if the <b>SwingAndTweet</b> application can log into your Twitter account, the try block will execute completely, and the catch block will not execute.</p>
<p>But if an error occurs when trying to log into your Twitter account, the try block will stop executing after the <b>twitter.verifyCredentials()</b> statement and will jump to the <b>JOptionPane.showMessageDialog (null, &quot;Login failed&quot;);</b> statement inside the catch block. The result will be a dialog box indicating the login process failed, and then the application will return to the main screen, without updating your Twitter status.</p>
<p>Inside the try block, the first line creates a <i>Twitter</i> object named <i>twitter</i> (yes, I know I could&rsquo;ve thought of a more creative name) with your <b>username</b> and your <b>password</b> as parameters. The next line:</p>
<pre style="margin-left: 40px;">twitter.verifyCredentials();
</pre>
<p>is the one in charge of verifying that you can log into your Twitter account. As I explained before, if an error occurs when trying to log in, an exception will be thrown up and the following lines of code will not execute, because the execution will jump to the line inside the catch block.</p>
<p>Now, if the login process is successful, the execution will continue with:&nbsp;</p>
<pre style="margin-left: 40px;">JOptionPane.showMessageDialog(null, &quot;You&#39;re logged in!&quot;);
</pre>
<p>This line is the one that shows the dialog window indicating you could log in successfully to your Twitter account. Then, when you press the OK button on this dialog, it will close and you&rsquo;ll return to the main screen of your <b>SwingAndTweet</b> application, and the next line of code will execute:</p>
<pre style="margin-left: 40px;">
<style type="text/css">
	<!--
		@page { margin: 0.79in }
		P { margin-bottom: 0.08in }
	-->
	</style>

java.util.List&lt;Status&gt; statusList = twitter.getUserTimeline();
</pre>
<p>In this line we create a List object called statusList, and we assign to this object the result returned by the getUserTimeline method of the twitter object. This method returns all the information regarding your 20 most recent Tweets.</p>
<p>On the next line, we create a <b>String</b> object called <b>s</b>, and we assign to it all the information regarding the text of your first Tweet only, through the <b>statusList.get(0).getText()</b> method. But first we need to use the <b>String.valueOf</b> method to convert the <b>Object</b> value returned by the <b>statusList.get(0).getText()</b> method into a <b>String</b> value that <b>s</b> can receive.</p>
<p>The last line:</p>
<div style="margin-left: 40px;">
<pre>jTextField1.setText(s);
</pre>
</div>
<p>assigns the value of the <b>s</b> string to the textbox control named <b>jTextField1</b>, so you can see your latest tweet in the <b>SwingAndTweet</b> main window.</p>
<h1>Summary</h1>
<p>In this article, we discussed how to go about building a custom application for Twitter using java and NetBeans.</p>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.allfreetech.com/java/swinging-and-tweeting-with-java-and-netbeans-129.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
