<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>ViralPatel.net</title> <link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/viralpatelnet" /><feedburner:info uri="viralpatelnet" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>viralpatelnet</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item><title>Convert Arrays to Set in Java</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/Tb0aZZoHu9I/convert-array-to-set-java-arraylist.html</link> <comments>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html#comments</comments> <pubDate>Tue, 24 Jan 2012 13:45:10 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[arraylists]]></category> <category><![CDATA[java collections]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2655</guid> <description><![CDATA[Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often. However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/f4xsmB1b1--CFAAifgrO07oJi_g/0/da"><img src="http://feedads.g.doubleclick.net/~a/f4xsmB1b1--CFAAifgrO07oJi_g/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/f4xsmB1b1--CFAAifgrO07oJi_g/1/da"><img src="http://feedads.g.doubleclick.net/~a/f4xsmB1b1--CFAAifgrO07oJi_g/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/java-logo1.gif" alt="java-logo" title="java-logo" width="100" height="160" class="alignright size-full wp-image-620" />Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often.</p><p>However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an <strong>Java Array to ArrayList</strong>, I have seen people writing loops instead of simple <code>Arrays.asList()</code>.</p><p>Here is a simple writeup on <a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html"><strong>Converting Java Arrays to ArrayList</strong></a> that I wrote a while ago.</p><p>One of such simple requirement is to convert Java <strong>Arrays to Set</strong>. While working with Hibernate, I once had to convert a Java Arrays that we used to populate from UI and convert it into <code>Set</code>. While this is a simple task, most often one may end up writing for loop.</p><p>Here is a dead simple trick. Use below code to <strong>Convert Arrays to Set</strong> in Java.</p><pre class="brush: java; gutter: false; title: ; notranslate">
Set&lt;T&gt; mySet = new HashSet&lt;T&gt;(Arrays.asList(someArray));
</pre><p>Tanaa!!! Simple isn&#8217;t it. Its like <em>&#8220;I already knew that&#8221;</em> stuff.</p><p>Notice how we have used Generics also in above code snippet. Thus if you have an <code>ArrayList<Foo></code> than you can convert it to Set<Foo> with one simple line of code.</p><p>Checkout below example:</p><h3>Example: Java Array to Set</h3><pre class="brush: java; title: ; notranslate">
String [] countires = {&quot;India&quot;, &quot;Switzerland&quot;, &quot;Italy&quot;}; 

Set&lt;String&gt; set = new HashSet&lt;String&gt;(Arrays.asList(countires));
System.out.println(set);
</pre><p><strong>Output:</strong></p><pre class="brush: plain; gutter: false; title: ; notranslate">
[Italy, Switzerland, India]
</pre><p>Hope this is useful.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html" title="Java Tip: How to Sort Arrays in Java using java.util.Arrays class">Java Tip: How to Sort Arrays in Java using java.util.Arrays class</a></li><li><a href="http://viralpatel.net/blogs/2011/12/spring-mvc-multi-row-submit-java-list.html" title="Spring MVC: Multiple Row Form Submit using List of Beans">Spring MVC: Multiple Row Form Submit using List of Beans</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/10/convert-string-to-enum-instance-string-enum-java.html" title="Convert String to Enum Instance in Java">Convert String to Enum Instance in Java</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2010/02/generate-pie-chart-bar-graph-in-pdf-using-itext-jfreechart.html" title="Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart">Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=Tb0aZZoHu9I:TgmF4DvyY9I:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html</feedburner:origLink></item> <item><title>STOP SOPA JQuery Plugin</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/mqE7NvUTFAg/stopsopa-jquery-plugin.html</link> <comments>http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html#comments</comments> <pubDate>Wed, 18 Jan 2012 11:48:30 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[JavaScript]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2641</guid> <description><![CDATA[Right now, Internet is experiencing the biggest protest since its inception. We have seen people protesting against Companies, Government, Dictators etc. Also Internet has become their voices in form of Twitter &#038; Facebook. But today we saw something completely new. Major websites such as Wikipedia and Google are openly demonstrating their protest against new legislation [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/A_VetkdYGUCWBFzCOi9dpNagDb0/0/da"><img src="http://feedads.g.doubleclick.net/~a/A_VetkdYGUCWBFzCOi9dpNagDb0/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/A_VetkdYGUCWBFzCOi9dpNagDb0/1/da"><img src="http://feedads.g.doubleclick.net/~a/A_VetkdYGUCWBFzCOi9dpNagDb0/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2012/01/stop-sopa.png" alt="stop-sopa" title="stop-sopa" width="143" height="140" class="alignright size-full wp-image-2642" />Right now, Internet is experiencing the biggest protest since its inception. We have seen people protesting against Companies, Government, Dictators etc. Also Internet has become their voices in form of Twitter &#038; Facebook.</p><p>But today we saw something completely new. Major websites such as Wikipedia and Google are openly demonstrating their protest against new legislation bills SOPA and PIPA which is right now being voted in U.S. Congress. The Senate will begin voting on January 24th.</p><p>Well, if you do support the STOPSOPA cause here is a coolest thing to do. Add a black colored STOPSOPA banner on your website!!!!</p><p>Here&#8217;s is the deal. I have created a simple JQuery plugin which you can include at the end of your website. And voila!!! It adds black color banner on top of your webpage saying &#8220;<strong>I  support #STOPSOPA campaign. Do you?</strong>&#8221;</p><p>Just include below javascript at the end of webpage:</p><pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;http://viralpatel.net/stopsopa/jquery.stopsopa.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
	$(document).ready(function() { $(this).stopsopa() });
&lt;/script&gt;
</pre><p>That&#8217;s All!!</p><p>Please note that I haven&#8217;t tested this plugin for cross browsers. Let me know in case you find difficulties in adding.</p><style>.demobtns
a{background:-moz-linear-gradient(center top , #BDED82, #83CC29) repeat scroll 0 0 transparent;border:1px
solid #5F961A;border-radius:7px 7px 7px 7px;color:#5F961A;display:inline-block;font-size:18px;margin-right:5px;padding:10px
9px}</style><div class="demobtns"> <a target="_new" href="http://viralpatel.net/stopsopa/">Demo</a></div><p><br/></p><h2>StopSOPA WordPress Plugin</h2><p>I have quickly assemble a small wordpress plugin to add StopSOPA message on your blog. Just in case you dont want to hack your lovely theme and add those javascripts, you can simply enable this plugin and voila; you have your own StopSOPA Blackout message.</p><p><strong>Update:</strong> The StopSOPA plugin is now available at WordPress Plugin Directory: <a rel="nofollow" href="http://wordpress.org/extend/plugins/stopsopa/"><strong>StopSOPA WP Plugin</strong></a></p><div class="demobtns"> <a target="_new" href="http://viralpatel.net/stopsopa/stopsopa.zip">Download StopSOPA Plugin</a></div><p><br/></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html" title="Create ZIP Files in JavaScript">Create ZIP Files in JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/01/javascript-array-remove-element-js-array-delete-element.html" title="JavaScript Array Remove an Element ">JavaScript Array Remove an Element </a></li><li><a href="http://viralpatel.net/blogs/2009/11/disable-back-button-browser-javascript.html" title="Disable Back Button in Browser using JavaScript">Disable Back Button in Browser using JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2009/10/create-search-engine-google-custom-search-api.html" title="Create your own Search Engine(Interface) using Google Custom Search API">Create your own Search Engine(Interface) using Google Custom Search API</a></li><li><a href="http://viralpatel.net/blogs/2009/09/default-text-label-textbox-javascript-jquery.html" title="Default Text Label in Textbox using JavaScript/jQuery">Default Text Label in Textbox using JavaScript/jQuery</a></li><li><a href="http://viralpatel.net/blogs/2009/08/javascript-mouse-scroll-event-down-example.html" title="Mouse Scroll Event Up/Down Example in JavaScript">Mouse Scroll Event Up/Down Example in JavaScript</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=mqE7NvUTFAg:P5G-vOG6iBY:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html/feed</wfw:commentRss> <slash:comments>6</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html</feedburner:origLink></item> <item><title>How To Create QR Codes in Java &amp; Servlet</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/8V10TiKI_Bc/create-qr-codes-java-servlet-qr-code-java.html</link> <comments>http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html#comments</comments> <pubDate>Mon, 16 Jan 2012 17:04:11 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[android]]></category> <category><![CDATA[java code]]></category> <category><![CDATA[QR Code]]></category> <category><![CDATA[servlet]]></category> <category><![CDATA[Servlets]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2621</guid> <description><![CDATA[Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/YHm9XcoCb8vuZJSGDBAY034KKMc/0/da"><img src="http://feedads.g.doubleclick.net/~a/YHm9XcoCb8vuZJSGDBAY034KKMc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/YHm9XcoCb8vuZJSGDBAY034KKMc/1/da"><img src="http://feedads.g.doubleclick.net/~a/YHm9XcoCb8vuZJSGDBAY034KKMc/1/di" border="0" ismap="true"></img></a></p><p>Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.</p><p>Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.</p><h2>Introduction to QR Codes</h2><p>A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (&#8220;modes&#8221;) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.</p><p><img src="http://img.viralpatel.net/2012/01/qr-code-viralpatel-net.png" alt="" title="qr-code-viralpatel-net" width="149" height="149" class="aligncenter size-full wp-image-2624" /></p><p>Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.</p><h2>Hello World QR Code in Java</h2><p><a rel="nofollow" target="_new" href="http://code.google.com/p/zxing/">Zebra Crossing (ZXing)</a> is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.</p><p>However <a rel="nofollow" target="_new" href="http://kenglxn.github.com/QRGen/">QRGen</a> is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.</p><p>On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:</p><p><a href="http://viralpatel.net/blogs/download/jar/zxing-core-1.7.jar">zxing-core-1.7.jar (346 KB)</a><br /> <a href="http://viralpatel.net/blogs/download/jar/zxing-j2se-1.7.jar">zxing-javase-1.7.jar (21 KB)</a></p><p>Also download the QRGen JAR File from their <a rel="nofollow" href="https://github.com/kenglxn/QRGen/blob/master/dist/qrgen-1.0.jar">download page</a>.</p><p>Include these JAR files in your Classpath and execute following Java code to generate QR Code.</p><pre class="brush: java; highlight: [14,15]; title: ; notranslate">
package net.viralpatel.qrcode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class Main {
	public static void main(String[] args) {
		ByteArrayOutputStream out = QRCode.from(&quot;Hello World&quot;)
										.to(ImageType.PNG).stream();

		try {
			FileOutputStream fout = new FileOutputStream(new File(
					&quot;C:\\QR_Code.JPG&quot;));

			fout.write(out.toByteArray());

			fout.flush();
			fout.close();

		} catch (FileNotFoundException e) {
			// Do Logging
		} catch (IOException e) {
			// Do Logging
		}
	}
}
</pre><p>The code is pretty straight forward. We used <code>QRCode</code> class to generate QR Code Stream and write the byte stream to a file <strong>C:\QR_Code.JPG</strong>.</p><h3>Download Source Code</h3><h4><a rel="nofollow" href="http://viralpatel-net-tutorials.googlecode.com/files/QR_Code_Java.zip">QR_Code_Java.zip (339 KB)</a></h4><p>If you open this JPEG file and scan using your iPhone or Android QR scanner, you&#8217;ll find a cool &#8220;Hello World&#8221; in it <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:</p><pre class="brush: java; title: ; notranslate">
// get QR file from text using defaults
File file = QRCode.from(&quot;Hello World&quot;).file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from(&quot;Hello World&quot;).stream();

// override the image type to be JPG
QRCode.from(&quot;Hello World&quot;).to(ImageType.JPG).file();
QRCode.from(&quot;Hello World&quot;).to(ImageType.JPG).stream();

// override image size to be 250x250
QRCode.from(&quot;Hello World&quot;).withSize(250, 250).file();
QRCode.from(&quot;Hello World&quot;).withSize(250, 250).stream();

// override size and image type
QRCode.from(&quot;Hello World&quot;).to(ImageType.GIF).withSize(250, 250).file();
QRCode.from(&quot;Hello World&quot;).to(ImageType.GIF).withSize(250, 250).stream();
</pre><h2>Website Link (URLs) QR Code in Java</h2><p>One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace &#8220;Hello World&#8221; string with the URL you want to encode in QR Code. Below is the code snippet:</p><pre class="brush: java; gutter: false; title: ; notranslate">
ByteArrayOutputStream out = QRCode.from(&quot;http://viralpatel.net&quot;)
				.to(ImageType.PNG).stream();
</pre><h2>QR Code in Servlet</h2><p>Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.</p><p>Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.</p><p>The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.</p><p><em>File: index.jsp</em></p><pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;QR Code in Java Servlet - viralpatel.net&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

	&lt;form action=&quot;qrservlet&quot; method=&quot;get&quot;&gt;
		&lt;p&gt;Enter Text to create QR Code&lt;/p&gt;
		&lt;input type=&quot;text&quot; name=&quot;qrtext&quot; /&gt;
		&lt;input type=&quot;submit&quot; value=&quot;Generate QR Code&quot; /&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>The magic happens in <code>QRCodeServlet.java</code>. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.</p><p><em>File: QRCodeServlet.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.qrcodes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class QRCodeServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String qrtext = request.getParameter(&quot;qrtext&quot;);

		ByteArrayOutputStream out = QRCode.from(qrtext).to(
				ImageType.PNG).stream();

		response.setContentType(&quot;image/png&quot;);
		response.setContentLength(out.size());

		OutputStream outStream = response.getOutputStream();

		outStream.write(out.toByteArray());

		outStream.flush();
		outStream.close();
	}
}
</pre><p>The below web.xml simply maps <code>QRCodeServlet.java</code> with <code>/qrservlet</code> URL.</p><p><em>File: web.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
		xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
		xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
		xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
		id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;

  &lt;display-name&gt;QR_Code_Servlet&lt;/display-name&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;QRCodeServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;net.viralpatel.qrcodes.QRCodeServlet&lt;/servlet-class&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;QRCodeServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/qrservlet&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;

&lt;/web-app&gt;
</pre><h3>Download Source Code</h3><h4><a rel="nofollow" href="http://viralpatel-net-tutorials.googlecode.com/files/QR_Code_Servlet.zip">QR_Code_Servlet.zip (340 KB)</a></h4><h3>Output</h3><p><img src="http://img.viralpatel.net/2012/01/qr-code-java-servlet-index.png" alt="qr-code-java-servlet-index" title="qr-code-java-servlet-index" width="370" height="251" class="aligncenter size-full wp-image-2628" /></p><p><img src="http://img.viralpatel.net/2012/01/qr-code-java-servlet-image.png" alt="qr-code-java-servlet-image" title="qr-code-java-servlet-image" width="370" height="251" class="aligncenter size-full wp-image-2630" /></p><p><br/></p><h2>Conclusion</h2><p>Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.</p><p>Hope you&#8217;ll like this <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/08/jsp-servlet-session-listener-tutorial-example-in-eclipse-tomcat.html" title="JSP Servlet Session Listener tutorial example in Eclipse &#038; Tomcat">JSP Servlet Session Listener tutorial example in Eclipse &#038; Tomcat</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/06/double-brace-initialization-in-java.html" title="Double Brace Initialization in Java!">Double Brace Initialization in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/varargs-in-java-variable-argument-method-in-java-5.html" title="Varargs in Java: Variable argument method in Java 5">Varargs in Java: Variable argument method in Java 5</a></li><li><a href="http://viralpatel.net/blogs/2009/05/20-useful-java-code-snippets-for-java-developers.html" title="20 very useful Java code snippets for Java Developers">20 very useful Java code snippets for Java Developers</a></li><li><a href="http://viralpatel.net/blogs/2009/04/http-proxy-setting-java-setting-proxy-java.html" title="HTTP Proxy setting in Java. Setting up proxy.">HTTP Proxy setting in Java. Setting up proxy.</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=8V10TiKI_Bc:zTqTLK922Ms:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=8V10TiKI_Bc:zTqTLK922Ms:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=8V10TiKI_Bc:zTqTLK922Ms:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=8V10TiKI_Bc:zTqTLK922Ms:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=8V10TiKI_Bc:zTqTLK922Ms:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=8V10TiKI_Bc:zTqTLK922Ms:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html/feed</wfw:commentRss> <slash:comments>6</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html</feedburner:origLink></item> <item><title>Facebook Style Scroll Fixed Header in JQuery</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/cOY94fGq6xE/scroll-fix-header-jquery-facebook.html</link> <comments>http://viralpatel.net/blogs/2012/01/scroll-fix-header-jquery-facebook.html#comments</comments> <pubDate>Wed, 11 Jan 2012 12:22:41 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JQuery]]></category> <category><![CDATA[facebook]]></category> <category><![CDATA[header]]></category> <category><![CDATA[JQuery Events]]></category> <category><![CDATA[mouse scroll event]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2613</guid> <description><![CDATA[While doing some UI changes of a website, we had to implement a FIX header which remains fix on top of screen while scrolling. Facebook has a similar header which remains on top of content. Now for this, there are number of jQuery plugins available out there! But in our case we weren&#8217;t allowed to [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/8GjUXTV_H7NM_58jZInQ0FD4liA/0/da"><img src="http://feedads.g.doubleclick.net/~a/8GjUXTV_H7NM_58jZInQ0FD4liA/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/8GjUXTV_H7NM_58jZInQ0FD4liA/1/da"><img src="http://feedads.g.doubleclick.net/~a/8GjUXTV_H7NM_58jZInQ0FD4liA/1/di" border="0" ismap="true"></img></a></p><p>While doing some UI changes of a website, we had to implement a FIX header which remains fix on top of screen while scrolling. Facebook has a similar header which remains on top of content.</p><p>Now for this, there are number of jQuery plugins available out there! But in our case we weren&#8217;t allowed to add any new plugins to the technology stack of application (I know it sucks <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> ). So here is a small JQuery based solution to make a DIV of header fixed on top of the screen while scrolling.</p><p><strong>Related:</strong> <a href="http://viralpatel.net/blogs/2009/08/javascript-mouse-scroll-event-down-example.html">Mouse Scroll Events in JQuery</a></p><h2>The HTML</h2><p>Below is the HTML code. It contain a simple div #header which we want to freeze at the top. Note that we have included JQuery directly from jquery.com site (In my application we have included older version of jquery from out tech stack).</p><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;HTML&gt;
&lt;HEAD&gt;
	&lt;script type=&quot;text/javascript&quot; src=&quot;http://code.jquery.com/jquery-latest.js&quot;&gt;&lt;/script&gt;
	&lt;title&gt;Scroll Fixed Header like Facebook in JQuery - viralpatel.net&lt;/title&gt;
&lt;/HEAD&gt;
&lt;BODY&gt;

&lt;div id=&quot;header&quot;&gt;
	&lt;h1&gt;Scroll Fix Header like Facebook in JQuery&lt;/h1&gt;
&lt;/div&gt;

&lt;p&gt;Some dumb text to add scrolling in page &lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;/p&gt;
&lt;p&gt;Some more dumb text to add scrolling in page &lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;/p&gt;
&lt;p&gt;Some more dumb text to add scrolling in page &lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;/p&gt;
&lt;p&gt;Some more dumb text to add scrolling in page &lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;/p&gt;

&lt;/BODY&gt;
&lt;/HTML&gt;
</pre><p>In above HTML, we added few lines &#8220;Some dumb text to add&#8230;&#8221; just to make page scrollable.</p><h2>The JQuery</h2><p>The JQuery code is pretty straight forward. Take a look:</p><pre class="brush: jscript; highlight: [4]; title: ; notranslate">
&lt;SCRIPT&gt;
$(document).ready(function() {

	var div = $('#header');
	var start = $(div).offset().top;

	$.event.add(window, &quot;scroll&quot;, function() {
		var p = $(window).scrollTop();
		$(div).css('position',((p)&gt;start) ? 'fixed' : 'static');
		$(div).css('top',((p)&gt;start) ? '0px' : '');
	});

});
&lt;/SCRIPT&gt;
</pre><p>We have added an event listener to &#8220;<strong>scroll</strong>&#8221; event. This handler function gets called each time scroll event is fired in browser.</p><p>Now we select the header element (highlighted in above code) and simply do some position stuff. We make the header div&#8217;s position <strong>fixed</strong> of <strong>static</strong> depending upon the state of scroll position. Also the <strong>top</strong> attribute is set to 0px in case we want to make it fix, when page is scrolled down.</p><h2>Online Demo</h2><style>.demobtns
a{background:-moz-linear-gradient(center top , #BDED82, #83CC29) repeat scroll 0 0 transparent;border:1px
solid #5F961A;border-radius:7px 7px 7px 7px;color:#5F961A;display:inline-block;font-size:18px;margin-right:5px;padding:10px
9px}</style><div class="demobtns"> <a target="_new" href="http://viralpatel.net/blogs/demo/jquery/scroll-fix-header-facebook/">Demo</a> <a target="_new" href="http://viralpatel.net/blogs/demo/jquery/scroll-fix-header-facebook/download.zip">Download</a></div><p><br/></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/12/jquery-live-events.html" title="jQuery Live Event">jQuery Live Event</a></li><li><a href="http://viralpatel.net/blogs/2009/04/tutorial-handle-browser-events-using-jquery-javascript-framework.html" title="Tutorial: Handle browser events using jQuery JavaScript framework">Tutorial: Handle browser events using jQuery JavaScript framework</a></li><li><a href="http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html" title="Create a Clearable TextBox with jQuery">Create a Clearable TextBox with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html" title="jQuery: Get the Text of Element without Child Element">jQuery: Get the Text of Element without Child Element</a></li><li><a href="http://viralpatel.net/blogs/2011/01/first-play-framework-gae-siena-application-tutorial-example.html" title="Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example">Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/12/dynamically-shortened-text-show-more-link-jquery.html" title="Dynamically shortened Text with &#8220;Show More&#8221; link using jQuery">Dynamically shortened Text with &#8220;Show More&#8221; link using jQuery</a></li><li><a href="http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html" title="jQuery Ajax &#8211; Handling unauthenticated requests via Ajax">jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=cOY94fGq6xE:y-CUS9KkMTo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=cOY94fGq6xE:y-CUS9KkMTo:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=cOY94fGq6xE:y-CUS9KkMTo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=cOY94fGq6xE:y-CUS9KkMTo:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=cOY94fGq6xE:y-CUS9KkMTo:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=cOY94fGq6xE:y-CUS9KkMTo:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/scroll-fix-header-jquery-facebook.html/feed</wfw:commentRss> <slash:comments>5</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/scroll-fix-header-jquery-facebook.html</feedburner:origLink></item> <item><title>Create ZIP Files in JavaScript</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/soWjnAFW7Qw/create-zip-file-javascript.html</link> <comments>http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html#comments</comments> <pubDate>Tue, 10 Jan 2012 08:44:11 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[gzip]]></category> <category><![CDATA[Javascript Compression]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2599</guid> <description><![CDATA[Zip is a very useful file type if I must say most used. It is the most used file format for data compression and archiving. There are number utilities available to create/generate Zip file. Also most of the programming languages comes up with API supporting to generate Zip files. I have written a couple of [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/ELJXFfN-JFMpOUUE5HICQs56ubw/0/da"><img src="http://feedads.g.doubleclick.net/~a/ELJXFfN-JFMpOUUE5HICQs56ubw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ELJXFfN-JFMpOUUE5HICQs56ubw/1/da"><img src="http://feedads.g.doubleclick.net/~a/ELJXFfN-JFMpOUUE5HICQs56ubw/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2012/01/zip-box-example.png" alt="zip-box-example" title="zip-box-example" width="244" height="226" class="alignleft size-full wp-image-2607" />Zip is a very useful file type if I must say most used. It is the most used file format for data compression and archiving. There are number utilities available to create/generate Zip file. Also most of the programming languages comes up with API supporting to generate Zip files. I have written a couple of articles for zipping/unzipping files in <a href="http://viralpatel.net/blogs/2008/11/creating-zip-and-jar-files-in-java.html">Java</a> and <a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html">PHP</a>.</p><p>While browsing internet, I came up to a very interesting website <a rel="nofollow" href="http://jszip.stuartk.co.uk/">http://jszip.stuartk.co.uk/</a>. This is JavaScript based API to generate Zip files on the fly! It&#8217;s very simple to use. All you need to do is to include the jszip javascript file in your HTML document and call its API.</p><p>Let us see how to generate a simple ZIP file in JavaScript.</p><h2>Hello world ZIP in JavaScript</h2><p>Let us create a helloworld ZIP file which contains two text files, hello1.txt and hello2.txt.</p><h4>Step 1. Import jszip JavaScript</h4><p>Include the jszip javascript file in the HTML document where you want to generate ZIP files. You can download the jszip package and include it in HTML or directly include the jszip javascript through git repository.</p><pre class="brush: xml; gutter: false; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;
		src=&quot;https://raw.github.com/Stuk/jszip/master/jszip.js&quot;&gt;&lt;/script&gt;
</pre><h4>Step 2. Generate Hello world ZIP</h4><p>Following code snippet is HTML file which contains Javascript code to generate ZIP file.</p><pre class="brush: xml; title: ; notranslate">
&lt;HTML&gt;
&lt;HEAD&gt;
	&lt;script type=&quot;text/javascript&quot; src=&quot;jszip.js&quot;&gt;&lt;/script&gt;
&lt;/HEAD&gt;

&lt;BODY&gt;

	&lt;input type=&quot;button&quot; onclick=&quot;create_zip()&quot; value=&quot;Create Zip&quot;&gt;&lt;/input&gt;

&lt;/BODY&gt;
&lt;SCRIPT&gt;

function create_zip() {
	var zip = new JSZip();
	zip.add(&quot;hello1.txt&quot;, &quot;Hello First World\n&quot;);
	zip.add(&quot;hello2.txt&quot;, &quot;Hello Second World\n&quot;);
	content = zip.generate();
	location.href=&quot;data:application/zip;base64,&quot; + content;
}

&lt;/SCRIPT&gt;
&lt;/HTML&gt;
</pre><p>In above code snippet, we have a button &#8220;Create Zip&#8221; which calls javascript function create_zip(). This function calls jszip API to generate ZIP file.</p><h2>Online Demo</h2><p>Check the online demo.</p><style>.demobtns
a{background-color:#B9E67E;border:1px
solid #538312;border-radius:7px 7px 7px 7px;color:#538312;display:inline-block;font-size:18px;margin-right:5px;padding:10px
9px}</style><div class="demobtns"> <a target="_new" href="http://viralpatel.net/blogs/demo/js/create-zip-file-javascript/">Demo</a> <a target="_new" href="http://viralpatel.net/blogs/demo/js/create-zip-file-javascript/download.zip">Download</a></div><h2>Filename Problem</h2><p>If you have tried above demo in Firefox or Safari, you may have noticed the file that is generated has weird name: e.g. b77AewqA7.zip.part. This is because of existing bugs <a rel="nofollow" href="https://bugzilla.mozilla.org/show_bug.cgi?id=367231">367231</a> and <a rel="nofollow" href="https://bugzilla.mozilla.org/show_bug.cgi?id=532230">532230</a>. However jszip comes with a unique workaround of this problem by using <a rel="nofollow" href="http://www.downloadify.info/">Downloadify</a>.</p><pre class="brush: jscript; title: ; notranslate">
zip = new JSZip();
zip.add(&quot;Hello.&quot;, &quot;hello.txt&quot;);
Downloadify.create('downloadify',{
...
  data: function(){
    return zip.generate();
  },
...
  dataType: 'base64'
});
</pre><p>Hope this basic demo will help you get going with Client side ZIP file creation in JavaScript.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/02/compress-php-css-js-javascript-optimize-website-performance.html" title="Compress PHP, CSS, JavaScript(JS) &#038; Optimize website performance.">Compress PHP, CSS, JavaScript(JS) &#038; Optimize website performance.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/increase-performance-of-website-by-compressing-javascript.html" title="Increase performance of website by compressing JavaScript.">Increase performance of website by compressing JavaScript.</a></li><li><a href="http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html" title="STOP SOPA JQuery Plugin">STOP SOPA JQuery Plugin</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/01/javascript-array-remove-element-js-array-delete-element.html" title="JavaScript Array Remove an Element ">JavaScript Array Remove an Element </a></li><li><a href="http://viralpatel.net/blogs/2009/11/disable-back-button-browser-javascript.html" title="Disable Back Button in Browser using JavaScript">Disable Back Button in Browser using JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2009/10/create-search-engine-google-custom-search-api.html" title="Create your own Search Engine(Interface) using Google Custom Search API">Create your own Search Engine(Interface) using Google Custom Search API</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=soWjnAFW7Qw:VIsRuAkO9ks:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=soWjnAFW7Qw:VIsRuAkO9ks:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=soWjnAFW7Qw:VIsRuAkO9ks:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=soWjnAFW7Qw:VIsRuAkO9ks:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=soWjnAFW7Qw:VIsRuAkO9ks:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=soWjnAFW7Qw:VIsRuAkO9ks:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html</feedburner:origLink></item> <item><title>Play Framework Modules: Divide and Conquer</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/MOqfgJqUWIY/play-framework-modules.html</link> <comments>http://viralpatel.net/blogs/2012/01/play-framework-modules.html#comments</comments> <pubDate>Tue, 03 Jan 2012 18:52:03 +0000</pubDate> <dc:creator>Sebastian Scarano</dc:creator> <category><![CDATA[JavaEE]]></category> <category><![CDATA[Play Framework]]></category> <category><![CDATA[Play-framework]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2581</guid> <description><![CDATA[It&#8217;s usually the case that you start developing an application and go on fulfilling requirements. When your application grows bigger you start to realize the convenience of separating it into different components. Moreover, when you develop your second or third application, your begin to recognize certain features that could be reused across different applications. These [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/rB8QCy4ang5sgWy037Ivb44rUyY/0/da"><img src="http://feedads.g.doubleclick.net/~a/rB8QCy4ang5sgWy037Ivb44rUyY/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/rB8QCy4ang5sgWy037Ivb44rUyY/1/da"><img src="http://feedads.g.doubleclick.net/~a/rB8QCy4ang5sgWy037Ivb44rUyY/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2011/01/Play-framework.png" alt="Play-framework" title="Play-framework" width="200" height="79" class="alignleft size-full wp-image-2136" />It&#8217;s usually the case that you start developing an application and go on fulfilling requirements. When your application grows bigger you start to realize the convenience of separating it into different components. Moreover, when you develop your second or third application, your begin to recognize certain features that could be reused across different applications.</p><p>These are two good reasons to modularize an application. Ideally we should aim at components with high <a rel="nofollow" title="Cohesion" href="http://en.wikipedia.org/wiki/Cohesion_(computer_science)">cohesion</a> and low <a rel="nofollow" title="Coupling" href="http://en.wikipedia.org/wiki/Coupling_(computer_science)">coupling</a>.</p><p>The Java language has proven itself quite fit to accomplish this kind of tasks. It provides general means to enforce the use of well defined API thru interfaces, abstract classes, etc.</p><p>Play framework developers think that this is perfectly fine for developing a general purpose library, but in the case of a web application reusability and modularization could be best achieved by other means. Have a look at this excerpt taken from <a rel="nofollow" href="http://www.playframework.org/documentation/latest/faq#aYouguysdontevenknowhowtoprograminJava...a">play framework&#8217;s FAQ</a>:</p><blockquote><p>Java itself is a very generic programming language and not originally designed for web application development. It is a very different thing to write a generic and reusable Java library and to create a web application. A web application itself doesn’t need to be designed to be reusable. You need less abstraction, less configuration. Reusability does exist for web applications, but through web service APIs rather than language-level integration.</p></blockquote><p>So when it comes to reusability, play provides us with a solution better suited for web applications.</p><h2>Play modules</h2><p>A <a rel="nofollow" href="http://www.playframework.org/documentation/latest/modules#what">module</a> is just another Play framework application. The only difference is that a module is not meant to be run on his own, it needs to be included into a containing application.</p><p>Nevertheless, there area a couple of differences between a module and a regular application, mainly that a module has no conf file (it has to be provided by the main application) and everything in a module is optional.</p><p>Doing is better than saying, so as usual we will look for a fine opportunity to make a simple module to show how it works.</p><h2>Creating a new play framework application and deploying it to the cloud</h2><p>As many of you already know, we are working on the <a rel="nofollow" href="http://playdoces.appspot.com/">spanish translation of play framework site</a>. We wanted to add web analytics to it so that we can see how people were using it.</p><p>So in order to follow this example, we&#8217;ll need a play framework app deployed somewhere on the Internet. Nowadays there are lots of Java hosting options available for free. Here you have a couple of tutorials for deploying on <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-12.5---deploy-to-openshift">openshift</a>, <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-14---deploy-to-gae">google application engine</a> and <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-13---deploy-to-heroku">heroku</a>.</p><p>First let&#8217;s create a play framework application, I&#8217;ll create the app at ~/devel/apps/module-test, you can choose whatever location you like, just be sure to update the commands appropriately.</p><p>To create the app, run the following command at an os prompt:</p><p><pre class="brush: plain; title: ; notranslate">
sas@ubuntu:~/devel/apps/module-test$ play new analytics-app
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~
~ play! 1.2.4, http://www.playframework.org
~
~ The new application will be created in /home/sas/Dropbox/Public/devel/play/apps/module-test/analytics-app
~ What is the application name? [analytics-app]
~
~ OK, the application is created.
~ Start it with : play run analytics-app
~ Have fun!
</pre><p>Now it would be a good time to deploy it somewhere. For this tutorial we will deploy it at openshift, you can use any host you want (For more information on setting up your environment for openshift deployment follow <a rel="nofollow" href="https://github.com/opensas/play-demo/wiki/Step-12.5---deploy-to-openshift">this tutorial</a>)</p><p>Create a new directory at ~/devel/apps/module-test/openshift, go to that directory and run:</p><pre class="brush: plain; title: ; notranslate">
rhc-create-app -l mymail@mail.com -p mypassword -t jbossas-7.0 -a analyticsapp

Attempting to create remote application space: analyticsapp
Now your new domain name is being propagated worldwide (this might take a minute)...
Pulling new repo down

[...]

Successfully created application: analyticsapp
</pre><p>Next, we&#8217;ll get rid of the demo app:</p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/openshift/analyticsapp
rm -fr pom.xml src
</pre><p>And we&#8217;ll compile and package the newly created app as an exploded war. Go to ~/devel/apps/module-test folder and run:</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test
play war analytics-app -o openshift/analyticsapp/deployments/ROOT.war
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~
~ play! 1.2.4, http://www.playframework.org
~
JPDA port 8000 is already used. Will try to use any free port for debugging
Listening for transport dt_socket at address: 53978
00:22:38,021 INFO  ~ Starting /home/sas/Dropbox/Public/devel/play/apps/module-test/analytics-app
00:22:39,891 INFO  ~ Precompiling ...
00:22:49,075 INFO  ~ Done.
~ Packaging current version of the framework and the application to /home/sas/Dropbox/Public/devel/play/apps/module-test/openshift/analyticsapp/deployments/ROOT.war ...
~ Done !
~
~ You can now load /home/sas/Dropbox/Public/devel/play/apps/module-test/openshift/analyticsapp/deployments/ROOT.war as a standard WAR into your servlet container
~ You can't use play standard commands to run/stop/debug the WAR application...
~ ... just use your servlet container commands instead
~
~ Have fun!
~
</pre></p><p>Now we just need to commit the application and push it to our git repo on openshift:</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/openshift/analyticsapp
touch deployments/ROOT.war.dodeploy
git add -A
git commit -m &quot;deploy play framework app&quot;
git push origin
</pre></p><p><em>Note: The first time it will take a couple of minutes to push the application, because of play framework libraries. Later pushes will be much quicker, git is smart enough to only send updated files.</em></p><p>And that&#8217;s it, you&#8217;ve just deployed your first app to red hat&#8217;s cloud. You can see it running at http://analyticsapp-opensas.rhcloud.com/ (of course, you&#8217;ll have to replace &#8220;opensas&#8221; with your own openshift user name).</p><h2>Google web analytics &#038; play framework</h2><p>Adding Google web analytics to a play app is really easy. You just need a gmail account, then go to <a rel="nofollow" href="http://www.google.com/analytics/">Google Analytics web site</a>, click on &#8220;sign up&#8221;, login with your gmail account, and complete all the required data.</p><p>In the account name enter &#8220;analytics-app&#8221;, in the website&#8217;s url enter http://analyticsapp-opensas.rhcloud.com, agree to the terms and conditions and click on &#8220;Create account&#8221;.</p><p>You&#8217;ll be taken to your analytics-app account page, there you can see the tracking code. You&#8217;ll just have to paste it in your app. So open the file at ~/devel/apps/module-test/analytics-app/app/views/main.html and paste the tracking code before the closing head tag, like this:</p><pre class="brush: jscript; title: ; notranslate">
[...]
        &lt;script src=&quot;@{'/public/javascripts/jquery-1.6.4.min.js'}&quot; type=&quot;text/javascript&quot; charset=&quot;${_response_encoding}&quot;&gt;&lt;/script&gt;
        #{get 'moreScripts' /}

&lt;script type=&quot;text/javascript&quot;&gt;

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

&lt;/script&gt;

    &lt;/head&gt;
    &lt;body&gt;
[...]
</pre><p><em>Note: Google will provide you with your own UA-XXXXXXXX-1 account code, so just copy and paste the code from your Google analytics account page, and NOT from this page!</em></p><p>Now you just have to generate the war folder, commit, and push it once again to openshift to deploy your changes. Every time you make a change you&#8217;ll have to follow these same steps to deploy it to openshift.</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test
play war analytics-app/ -o openshift/analyticsapp/deployments/ROOT.war
cd openshift/analyticsapp/
git add -A
git commit -m &quot;added tracking code&quot;
git push origin
</pre></p><p>Visit again your page at http://analyticsapp-opensas.rhcloud.com/, and see the source of the page to check that the tracking code has been added. You can also see it in action on Google&#8217;s analytics page, click on &#8220;Home&#8221;, Real-Time (BETA), and the Overview. You should have one visitor (yes, it&#8217;s you!).</p><p>So far now we created a new play application and deployed it to openshift. Then we created a Google analytic account and added the tracking code the our play application. Everything is working ok and our app is being tracked by Google. Now we are going to move that functionality to a module so that we can reuse it from other apps.</p><h2>Creating a module</h2><p>To create a new module you have to use the &#8220;new-module&#8221; play command, like this:</p><p><pre class="brush: plain; title: ; notranslate">
cd /home/sas/devel/apps/module-test/
play new-module analytics
</pre></p><p>Now, in order to tell our main application (in our case analytics-app) to include this module, we have to configure a <a rel="nofollow" href="http://www.playframework.org/documentation/latest/dependency#Localrepositories">local repository</a>.</p><p>Edit ~/devel/apps/module-test/analytics-app/conf/dependencies.yml like this:</p><p><pre class="brush: plain; title: ; notranslate">
# Application dependencies

require:
    - play
    - analytics -&gt; analytics

repositories:
    - My local modules:
        type:       local
        artifact:   ${application.path}/../[module]
        contains:
            - analytics
</pre></p><p>and after that run the following command to tell play to resolve dependencies.</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/analytics-app
play dependencies
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~
~ play! 1.2.4, http://www.playframework.org
~
~ Resolving dependencies using /home/sas/devel/apps/module-test/analytics-app/conf/dependencies.yml,
~
~ 	analytics-&gt;analytics -&gt; (from My local modules)
~
~ Installing resolved dependencies,
~
~ 	modules/analytics -&gt; /home/sas/devel/apps/module-test/analytics/../analytics
~
~ Done!
~
</pre></p><p>You can now start the main application on your workstation:</p><p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/analytics-app
play run
</pre></p><p>You can see your app running at <a rel="nofollow" href="http://localhost:9000">http://localhost:9000</a>.</p><h2>Moving the tracking code to a reusable tag</h2><p>Now we will move the tracking code to a tag defined in the module, so we&#8217;ll create a file ~/devel/apps/module-test/analytics/app/views/analytics.html with the tracking code, like this:</p><pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

&lt;/script&gt;
</pre><p>And now, replace the tracking code in main.html with a call to the tag, like this:</p><pre class="brush: jscript; title: ; notranslate">
[...]
        &lt;script src=&quot;@{'/public/javascripts/jquery-1.6.4.min.js'}&quot; type=&quot;text/javascript&quot; charset=&quot;${_response_encoding}&quot;&gt;&lt;/script&gt;

        #{get 'moreScripts' /}

#{analytics /}
    &lt;/head&gt;
[...]
</pre><h2>Getting module configuration from the application.conf file</h2><p>Our module is almost ready, there&#8217;s just one thing that&#8217;s preventing us from really reusing it on another application: the Google analytics code is hardcoded in our tag!</p><p>So we will read it from the application.conf file. Just edit the analytics.html tag like this:</p><pre class="brush: jscript; title: ; notranslate">
%{
    String code = play.Play.configuration.getProperty(&quot;analytics.code&quot;, &quot;&quot;)
}%
#{if code!=&quot;&quot;}

&lt;script type=&quot;text/javascript&quot;&gt;
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '${code}}']);
  _gaq.push(['_trackPageview']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
&lt;/script&gt;
#{/if}
</pre><p>and add the following to your main application configuration file at ~/devel/apps/module-test/analytics-app/conf/application.conf</p><pre class="brush: jscript; gutter: false; title: ; notranslate">
analytics.code=UA-XXXXXXXX-1
</pre><h2>Prevent tracking in dev mode</h2><p>This tag will will update the tracker every time the page is rendered, even when we are working on our development workstation!</p><p>So we will add a minor improvement to prevent the module from logging the page activity while working in development mode.</p><p>Just add the following condition to the code:</p><pre class="brush: plain; title: ; notranslate">
%{
    String code = play.Play.configuration.getProperty(&quot;analytics.code&quot;, &quot;&quot;)
}%
#{if play.mode.isProd() &amp;&amp; code!=&quot;&quot;}
&lt;script type=&quot;text/javascript&quot;&gt;

  var _gaq = _gaq || [];
[...]
</pre><h2>Troubleshooting Openshift</h2><p>Openshift won&#8217;t be able to resolve the relative reference to the module location (and in fact any war deployed application will have the same problem), so you&#8217;ll have to tell play to copy the module sources to the containing application before generating the war folder. Just issue:</p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test/analytics-app
play dependencies --forceCopy
</pre><p>And that&#8217;s it, now you can deploy to openshift in the usual way:</p><pre class="brush: plain; title: ; notranslate">
cd ~/devel/apps/module-test
play war analytics-app/ -o openshift/analyticsapp/deployments/ROOT.war
cd openshift/analyticsapp/
git add -A
git commit -m &quot;added analytics module&quot;

git push origin
</pre><p>Run your site locally with &#8220;play run&#8221;, and also open it from <a rel="nofollow" href="http://analyticsapp-opensas.rhcloud.com/">http://analyticsapp-opensas.rhcloud.com/</a>, check the source code of both sites, you should see that the app running at openshift contains the tracking code, contrary to your local application.</p><h2>Conclusion</h2><p>In this post we saw how to deploy a play framework app to openshift and, more important, how to move features from your application to a module in order to reuse it from other applications.</p><p>You can learn more about modules on <a rel="nofollow" href="http://playframework.wordpress.com/2011/02/27/play-modules/">this article</a> or reading the <a rel="nofollow" href="http://www.playframework.org/documentation/latest/modules">play framework documentation</a>.</p><p>If you speak spanish you can <a rel="nofollow" href="http://playdoces.appspot.com/documentation/latest/translation">help us with the translation</a>, and you can also have a look at our work right <a rel="nofollow" href="http://playdoces.appspot.com/documentation/latest/modules">here</a>&#8230; You can be sure every click you make will be tracked!</p><p><i>From: <a rel="nofollow" href="http://playlatam.wordpress.com">http://playlatam.wordpress.com</a></i></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/01/first-play-framework-gae-siena-application-tutorial-example.html" title="Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example">Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=MOqfgJqUWIY:kOEhikFBhbo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=MOqfgJqUWIY:kOEhikFBhbo:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=MOqfgJqUWIY:kOEhikFBhbo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=MOqfgJqUWIY:kOEhikFBhbo:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=MOqfgJqUWIY:kOEhikFBhbo:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=MOqfgJqUWIY:kOEhikFBhbo:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/play-framework-modules.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/play-framework-modules.html</feedburner:origLink></item> <item><title>Hibernate Inheritance: Table Per Concrete Class (Annotation &amp; XML mapping)</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/gidRbLvPaQQ/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html#comments</comments> <pubDate>Fri, 30 Dec 2011 12:45:45 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[xml]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2509</guid> <description><![CDATA[Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table per Subclass. Today we will see how to implement Hibernate Inheritance: One Table per Concrete Class scheme. You may want to look at previous tutorials. Here is the complete list for you. Introduction to Inheritance in Hibernate [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/yLxJ7a7Wxku15G1PfQyZ0L2T6RA/0/da"><img src="http://feedads.g.doubleclick.net/~a/yLxJ7a7Wxku15G1PfQyZ0L2T6RA/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/yLxJ7a7Wxku15G1PfQyZ0L2T6RA/1/da"><img src="http://feedads.g.doubleclick.net/~a/yLxJ7a7Wxku15G1PfQyZ0L2T6RA/1/di" border="0" ismap="true"></img></a></p><p>Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table per Subclass.</p><p>Today we will see how to implement Hibernate Inheritance: One Table per Concrete Class scheme.</p><p>You may want to look at previous tutorials. Here is the complete list for you.</p><p><br/></p><h2>Introduction to Inheritance in Hibernate</h2><p>Java is an object oriented language. It is possible to implement Inheritance in Java. Inheritance is one of the most visible facets of Object-relational mismatch. Object oriented systems can model both <strong>&#8220;is a&#8221;</strong> and <strong>&#8220;has a&#8221;</strong> relationship. Relational model supports only &#8220;has a&#8221; relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs.</p><h2>One Table per Concrete Class example</h2><p>Suppose we have a class Person with subclasses Employee and Owner. Following the class diagram and relationship of these classes.</p><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-subclass-class-diagram-uml.png" alt="hibernate-table-per-subclass-class-diagram-uml" title="hibernate-table-per-subclass-class-diagram-uml" width="350" height="193" class="aligncenter size-full wp-image-2481" /></p><p>In One Table per Concrete class scheme, each concrete class is mapped as normal persistent class. Thus we have 3 tables; PERSON, EMPLOYEE and OWNER to persist the class data. In this scheme, the mapping of the subclass repeats the properties of the parent class.</p><p>Following are the advantages and disadvantages of One Table per Subclass scheme.</p><h4>Advantages</h4><ul><li>This is the easiest method of Inheritance mapping to implement.</li></ul><h4>Disadvantages</h4><ul><li>Data thats belongs to a parent class is scattered across a number of subclass tables, which represents concrete classes.</li><li>This hierarchy is not recommended for most cases.</li><li>Changes to a parent class is reflected to large number of tables</li><li>A query couched in terms of parent class is likely to cause a large number of select operations</li></ul><p>This strategy has many drawbacks (esp. with polymorphic queries and associations) explained in the JPA spec, the Hibernate reference documentation, Hibernate in Action, and many other places. Hibernate work around most of them implementing this strategy using SQL UNION queries. It is commonly used for the top level of an inheritance hierarchy:</p><h2>Create Database Table to persist Concrete classes</h2><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `person` (
	`person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL DEFAULT '0',
	`lastname` VARCHAR(50) NOT NULL DEFAULT '0',
	PRIMARY KEY (`person_id`)
)

CREATE TABLE `employee` (
	`person_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL,
	`lastname` VARCHAR(50) NOT NULL,
	`joining_date` DATE NULL DEFAULT NULL,
	`department_name` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`)
)

CREATE TABLE `owner` (
	`person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL DEFAULT '0',
	`lastname` VARCHAR(50) NOT NULL DEFAULT '0',
	`stocks` BIGINT(11) NULL DEFAULT NULL,
	`partnership_stake` BIGINT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`)
)
</pre><p><br/></p><h2>Project Structure in Eclipse</h2><h4>For XML mapping</h4><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-concrete-class-xml-project-structure.png" alt="hibernate-table-per-concrete-class-xml-project-structure" title="hibernate-table-per-concrete-class-xml-project-structure" width="262" height="343" class="aligncenter size-full wp-image-2512" /></p><h4>For Annotation mapping</h4><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-concrete-class-annotation-project-structure.png" alt="hibernate-table-per-concrete-class-annotation-project-structure" title="hibernate-table-per-concrete-class-annotation-project-structure" width="263" height="325" class="aligncenter size-full wp-image-2513" /><br /> <br/></p><h2>Hibernate Inheritance: XML Mapping</h2><p>Following is the example where we map Person, Employee and Owner entity classes using XML mapping.</p><p><em>File: Person.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Person {

	private Long personId;
	private String firstname;
	private String lastname;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Employee.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

public class Employee extends Person {

	private Date joiningDate;
	private String departmentName;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Owner extends Person {

		private Long stocks;
		private Long partnershipStake;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Person.hbm.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Person&quot; table=&quot;PERSON&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;

	&lt;/class&gt;

	&lt;class name=&quot;Employee&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;
		&lt;property name=&quot;departmentName&quot; column=&quot;department_name&quot; /&gt;
		&lt;property name=&quot;joiningDate&quot; type=&quot;date&quot; column=&quot;joining_date&quot; /&gt;
	&lt;/class&gt;

	&lt;class name=&quot;Owner&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;
		&lt;property name=&quot;stocks&quot; column=&quot;stocks&quot; /&gt;
		&lt;property name=&quot;partnershipStake&quot; column=&quot;partnership_stake&quot; /&gt;
	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><br/></p><p>Note that we have defined only one hibernate mapping (hbm) file <code>Person.hbm.xml</code>. Both <code>Person</code> and <code>Employee</code> model class are defined within one hbm file.</p><p>We mapped all the classes using simple &lt;class&gt; tag in hbm. This is the usual way of mapping classes in XML.</p><h2>Hibernate Inheritance: Annotation Mapping</h2><p>Following is the example where we map Person, Employee and Owner entity classes using JPA Annotations.</p><p><em>File: Person.java</em></p><pre class="brush: java; highlight: [12]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name = &quot;PERSON&quot;)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person {

	@Id
	@Column(name = &quot;PERSON_ID&quot;)
	private Long personId;

	@Column(name = &quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name = &quot;LASTNAME&quot;)
	private String lastname;

	public Person() {

	}
	public Person(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}
	// Getter and Setter methods,
}
</pre><p><br/></p><p><strong><code>@Inheritance</code></strong> &#8211; Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.</p><p><strong><code>@InheritanceType</strong></code> &#8211; Defines inheritance strategy options. TABLE_PER_CLASS is a strategy to map table per concrete class.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [13,14,15,16]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
@AttributeOverrides({
    @AttributeOverride(name=&quot;firstname&quot;, column=@Column(name=&quot;FIRSTNAME&quot;)),
    @AttributeOverride(name=&quot;lastname&quot;, column=@Column(name=&quot;LASTNAME&quot;))
})
public class Employee extends Person {

	@Column(name=&quot;joining_date&quot;)
	private Date joiningDate;

	@Column(name=&quot;department_name&quot;)
	private String departmentName;

	public Employee() {
	}

	public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {

		super(firstname, lastname);

		this.departmentName = departmentName;
		this.joiningDate = joiningDate;
	}

	// Getter and Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; highlight: [11,12,13,14]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name=&quot;OWNER&quot;)
@AttributeOverrides({
    @AttributeOverride(name=&quot;firstname&quot;, column=@Column(name=&quot;FIRSTNAME&quot;)),
    @AttributeOverride(name=&quot;lastname&quot;, column=@Column(name=&quot;LASTNAME&quot;))
})
public class Owner extends Person {

	@Column(name=&quot;stocks&quot;)
	private Long stocks;

	@Column(name=&quot;partnership_stake&quot;)
	private Long partnershipStake;

	public Owner() {
	}

	public Owner(String firstname, String lastname, Long stocks, Long partnershipStake) {

		super(firstname, lastname);

		this.stocks = stocks;
		this.partnershipStake = partnershipStake;
	}

	// Getter and Setter methods,
}
</pre><p><br/></p><p>Both Employee and Owner classes are child of Person class. Thus while specifying the mappings, we used <code>@AttributeOverrides</code> to map them.</p><p><strong><code>@AttributeOverrides</strong></code> &#8211; This annotation is used to override mappings of multiple properties or fields.</p><p><strong><code>@AttributeOverride</strong></code> &#8211; The AttributeOverride annotation is used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field.</p><p>The AttributeOverride annotation may be applied to an entity that extends a mapped superclass or to an embedded field or property to override a basic mapping defined by the mapped superclass or embeddable class. If the AttributeOverride annotation is not specified, the column is mapped the same as in the original mapping.</p><p>Thus in over case, firstname and lastname are defined in parent class Person and mapped in child class Employee and Owner using @AttributeOverrides annotation.</p><p>This strategy supports one-to-many associations provided that they are bidirectional. This strategy does not support the IDENTITY generator strategy: the id has to be shared across several tables. Consequently, when using this strategy, you should not use AUTO nor IDENTITY. Note that in below Main class we specified the primary key explicitly.</p><h2>Main class</h2><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Person person = new Person(&quot;Steve&quot;, &quot;Balmer&quot;);
		person.setPersonId(1L);
		session.save(person);

		Employee employee = new Employee(&quot;James&quot;, &quot;Gosling&quot;, &quot;Marketing&quot;, new Date());
		employee.setPersonId(2L);
		session.save(employee);

		Owner owner = new Owner(&quot;Bill&quot;, &quot;Gates&quot;, 300L, 20L);
		owner.setPersonId(3L);
		session.save(owner);

		session.getTransaction().commit();
		session.close();

	}
}
</pre><p>The Main class is used to persist <code>Person</code>, <code>Employee</code> and <code>Owner</code> object instances. Note that these classes are persisted in different tables and parent attributes (firstname, lastname) are repeated across all tables.</p><h4>Output</h4><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into PERSON (FIRSTNAME, LASTNAME, PERSON_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, department_name, joining_date, PERSON_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into OWNER (FIRSTNAME, LASTNAME, partnership_stake, stocks, PERSON_ID) values (?, ?, ?, ?, ?)
</pre><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-concrete-class-output.png" alt="hibernate-table-per-concrete-class-output" title="hibernate-table-per-concrete-class-output" width="459" height="204" class="aligncenter size-full wp-image-2511" /></p><p><br/></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-concrete-class_xml.zip">Hibernate-inheritance-table-per-concrete-class_xml.zip (9 KB)</a></em><br /> <em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-concrete-class_annotation.zip">Hibernate-inheritance-table-per-concrete-class_annotation.zip (9 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html" title="Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)">Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html" title="Hibernate Self Join Annotations One To Many mapping example">Hibernate Self Join Annotations One To Many mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=gidRbLvPaQQ:v9DZC-lKTS4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=gidRbLvPaQQ:v9DZC-lKTS4:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=gidRbLvPaQQ:v9DZC-lKTS4:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=gidRbLvPaQQ:v9DZC-lKTS4:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=gidRbLvPaQQ:v9DZC-lKTS4:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=gidRbLvPaQQ:v9DZC-lKTS4:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html</feedburner:origLink></item> <item><title>Hibernate Inheritance: Table Per Subclass (Annotation &amp; XML mapping)</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/nNCp4v1nUsE/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html#comments</comments> <pubDate>Tue, 27 Dec 2011 09:40:15 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[hibernate-configuration]]></category> <category><![CDATA[Inheritance]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2479</guid> <description><![CDATA[Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table Per Hierarchy. Today we will see how to implement Hibernate Inheritance: One Table per Subclass scheme. You may want to look at previous tutorials. Here is the complete list for you. Introduction to Inheritance in Hibernate Java [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/lFNO-D0btsxwGb-LXoavYVXjMtk/0/da"><img src="http://feedads.g.doubleclick.net/~a/lFNO-D0btsxwGb-LXoavYVXjMtk/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/lFNO-D0btsxwGb-LXoavYVXjMtk/1/da"><img src="http://feedads.g.doubleclick.net/~a/lFNO-D0btsxwGb-LXoavYVXjMtk/1/di" border="0" ismap="true"></img></a></p><p>Welcome to Hibernate Tutorial Series. In previous tutorials we saw how to implement Inheritance in Hibernate: One Table Per Hierarchy.</p><p>Today we will see how to implement Hibernate Inheritance: One Table per Subclass scheme.</p><p>You may want to look at previous tutorials. Here is the complete list for you.</p><p><br/></p><h2>Introduction to Inheritance in Hibernate</h2><p>Java is an object oriented language. It is possible to implement Inheritance in Java. Inheritance is one of the most visible facets of Object-relational mismatch. Object oriented systems can model both <strong>&#8220;is a&#8221;</strong> and <strong>&#8220;has a&#8221;</strong> relationship. Relational model supports only &#8220;has a&#8221; relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs.</p><h2>One Table Per Subclass example</h2><p>Suppose we have a class Person with subclass Employee and Owner. Following the class diagram and relationship of these classes.</p><p><img src="http://img.viralpatel.net/2011/12/hibernate-table-per-subclass-class-diagram-uml.png" alt="hibernate-table-per-subclass-class-diagram-uml" title="hibernate-table-per-subclass-class-diagram-uml" width="350" height="193" class="aligncenter size-full wp-image-2481" /></p><p>In One Table per Subclass scheme, each class persist the data in its own separate table. Thus we have 3 tables; PERSON, EMPLOYEE and OWNER to persist the class data. Note that a foreign key relationship exists between the subclass tables and super class table. Thus the common data is stored in PERSON table and subclass specific fields are stored in EMPLOYEE and OWNER tables.</p><p>Following are the advantages and disadvantages of One Table per Subclass scheme.</p><h4>Advantage</h4><ul><li>Using this hierarchy, does not require complex changes to the database schema when a single parent class is modified.</li><li>It works well with shallow hierarchy.</li></ul><h4>Disadvantage</h4><ul><li>As the hierarchy grows, it may result in poor performance.</li><li>The number of joins required to construct a subclass also grows.</li></ul><h2>Create Database Table to persist Subclass</h2><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `person` (
	`person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NOT NULL DEFAULT '0',
	`lastname` VARCHAR(50) NOT NULL DEFAULT '0',
	PRIMARY KEY (`person_id`)
)

CREATE TABLE `employee` (
	`person_id` BIGINT(10) NOT NULL,
	`joining_date` DATE NULL DEFAULT NULL,
	`department_name` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`),
	CONSTRAINT `FK_PERSON` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
)

CREATE TABLE `owner` (
	`person_id` BIGINT(20) NOT NULL DEFAULT '0',
	`stocks` BIGINT(11) NULL DEFAULT NULL,
	`partnership_stake` BIGINT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`person_id`),
	CONSTRAINT `FK_PERSON2` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
)
</pre><p><br/></p><h2>Hibernate Inheritance: XML Mapping</h2><p>Following is the example where we map Person, Employee and Owner entity classes using XML mapping.</p><p><em>File: Person.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Person {

	private Long personId;
	private String firstname;
	private String lastname;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Employee.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

public class Employee extends Person {

	private Date joiningDate;
	private String departmentName;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class Owner extends Person {

		private Long stocks;
		private Long partnershipStake;

	// Constructors and Getter/Setter methods,
}
</pre><p><em>File: Person.hbm.xml</em></p><pre class="brush: java; highlight: [16,21]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Person&quot; table=&quot;PERSON&quot;&gt;
		&lt;id name=&quot;personId&quot; column=&quot;PERSON_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;

		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;

		&lt;joined-subclass name=&quot;Employee&quot; extends=&quot;Person&quot;&gt;
				&lt;key column=&quot;person_id&quot; /&gt;
				&lt;property name=&quot;departmentName&quot; column=&quot;department_name&quot; /&gt;
				&lt;property name=&quot;joiningDate&quot; type=&quot;date&quot; column=&quot;joining_date&quot; /&gt;
		&lt;/joined-subclass&gt;
		&lt;joined-subclass name=&quot;Owner&quot; extends=&quot;Person&quot;&gt;
				&lt;key column=&quot;person_id&quot; /&gt;
				&lt;property name=&quot;stocks&quot; column=&quot;stocks&quot; /&gt;
				&lt;property name=&quot;partnershipStake&quot; column=&quot;partnership_stake&quot; /&gt;
		&lt;/joined-subclass&gt;
	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><br/></p><p>Note that we have defined only one hibernate mapping (hbm) file <code>Person.hbm.xml</code>. Both <code>Person</code> and <code>Employee</code> model class are defined within one hbm file.</p><p><strong>&lt;discriminator&gt;</strong> tag is used to define the discriminator column.</p><p><strong>&lt;subclass&gt;</strong> tag is used to map the subclass Employee. Note that we have not used the usual <code>&lt;class&gt;</code> tag to map Employee as it falls below in the hierarchy tree.</p><p>The discriminator-value for <code>Person</code> is defined as <em>&#8220;P&#8221;</em> and that for <code>Employee</code> is defined <em>&#8220;E&#8221;</em>, Thus, when Hibernate will persist the data for person or employee it will accordingly populate this value.</p><h2>Hibernate Inheritance: Annotation Mapping</h2><p>Following is the example where we map Employee and Person entity classes using JPA Annotations.</p><p><em>File: Person.java</em></p><pre class="brush: java; highlight: [13]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name = &quot;PERSON&quot;)
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {

	@Id
	@GeneratedValue
	@Column(name = &quot;PERSON_ID&quot;)
	private Long personId;

	@Column(name = &quot;FIRSTNAME&quot;)
	private String firstname;

	@Column(name = &quot;LASTNAME&quot;)
	private String lastname;

	public Person() {

	}
	public Person(String firstname, String lastname) {
		this.firstname = firstname;
		this.lastname = lastname;
	}

	// Getter and Setter methods,
}
</pre><p><br/></p><p>The <code>Person</code> class is the root of hierarchy. Hence we have used some annotations to make it as the root.</p><p><strong><code>@Inheritance</code></strong> &#8211; Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.</p><p><strong><code>@InheritanceType</strong></code> &#8211; Defines inheritance strategy options. JOINED is a strategy in which fields that are specific to a subclass are mapped to a separate table than the fields that are common to the parent class, and a join is performed to instantiate the subclass. Thus fields of Employee (joining_date, department) and Owner (stocks etc) are mapped to their respective tables.</p><p><em>File: Employee.java</em></p><pre class="brush: java; highlight: [12]; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
@PrimaryKeyJoinColumn(name=&quot;PERSON_ID&quot;)
public class Employee extends Person {

	@Column(name=&quot;joining_date&quot;)
	private Date joiningDate;

	@Column(name=&quot;department_name&quot;)
	private String departmentName;

	public Employee() {
	}

	public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {

		super(firstname, lastname);

		this.departmentName = departmentName;
		this.joiningDate = joiningDate;
	}

	// Getter and Setter methods,
}
</pre><p><em>File: Owner.java</em></p><pre class="brush: java; highlight: [10]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@Table(name=&quot;OWNER&quot;)
@PrimaryKeyJoinColumn(name=&quot;PERSON_ID&quot;)
public class Owner extends Person {

	@Column(name=&quot;stocks&quot;)
	private Long stocks;

	@Column(name=&quot;partnership_stake&quot;)
	private Long partnershipStake;

	public Owner() {
	}

	public Owner(String firstname, String lastname, Long stocks, Long partnershipStake) {

		super(firstname, lastname);

		this.stocks = stocks;
		this.partnershipStake = partnershipStake;
	}

	// Getter and Setter methods,
}
</pre><p><br/></p><p>Both Employee and Owner classes are child of Person class. Thus while specifying the mappings, we used <code>@PrimaryKeyJoinColumn</code> to map it to parent table.</p><p><strong><code>@PrimaryKeyJoinColumn</strong></code> &#8211; This annotation specifies a primary key column that is used as a foreign key to join to another table.</p><p>It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.</p><p>If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass</p><h2>Main class</h2><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Person person = new Person(&quot;Steve&quot;, &quot;Balmer&quot;);
		session.save(person);

		Employee employee = new Employee(&quot;James&quot;, &quot;Gosling&quot;, &quot;Marketing&quot;, new Date());
		session.save(employee);

		Owner owner = new Owner(&quot;Bill&quot;, &quot;Gates&quot;, 300L, 20L);
		session.save(owner);

		session.getTransaction().commit();
		session.close();

	}
}
</pre><p>The Main class is used to persist <code>Person</code>, <code>Employee</code> and <code>Owner</code> object instances. Note that these classes are persisted in different tables.</p><h4>Output</h4><pre class="brush: sql; gutter: false; title: ; notranslate">
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into Employee (department_name, joining_date, person_id) values (?, ?, ?)
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into Owner (stocks, partnership_stake, person_id) values (?, ?, ?)
</pre><p><img src="http://img.viralpatel.net/2011/12/hibernate-inheritance-table-per-subclass-table-output.png" alt="hibernate-inheritance-table-per-subclass-table-output" title="hibernate-inheritance-table-per-subclass-table-output" width="314" height="240" class="aligncenter size-full wp-image-2496" /></p><p><br/></p><h2>Download Source Code</h2><p><em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-subclass_xml.zip">Hibernate-inheritance-table-per-subclass_xml.zip (9 KB)</a></em><br /> <em><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-inheritance-table-per-subclass_annotation.zip">Hibernate-inheritance-table-per-subclass_annotation.zip (9 KB)</a></em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html" title="Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)">Hibernate Inheritance: Table Per Class Hierarchy (Annotation &#038; XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html" title="Introduction to Hibernate framework">Introduction to Hibernate framework</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=nNCp4v1nUsE:qsZcQoLyGgU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=nNCp4v1nUsE:qsZcQoLyGgU:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=nNCp4v1nUsE:qsZcQoLyGgU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=nNCp4v1nUsE:qsZcQoLyGgU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=nNCp4v1nUsE:qsZcQoLyGgU:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=nNCp4v1nUsE:qsZcQoLyGgU:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html</feedburner:origLink></item> <item><title>How To Reset MySQL Autoincrement Column</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/OCBWqmW2p6o/reseting-mysql-autoincrement-column.html</link> <comments>http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html#comments</comments> <pubDate>Thu, 22 Dec 2011 07:31:38 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[database indexes]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[mysqldump]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2473</guid> <description><![CDATA[MySQL database provides a wonderful feature of Autoincrement Column index. Your database table can define its primary key as Autoincrement number and MySQL will take care of its unique value while inserting new rows. Each time you add a new row, MySQL increments the value automatically and persist it to table. But sometime you may [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/FFjdHlFAlm30A6BZf1bMgtzlRaU/0/da"><img src="http://feedads.g.doubleclick.net/~a/FFjdHlFAlm30A6BZf1bMgtzlRaU/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/FFjdHlFAlm30A6BZf1bMgtzlRaU/1/da"><img src="http://feedads.g.doubleclick.net/~a/FFjdHlFAlm30A6BZf1bMgtzlRaU/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/mysql-logo.png" alt="mysql-logo" title="mysql-logo" width="187" height="118" class="alignright size-full wp-image-669" />MySQL database provides a wonderful feature of <a href="http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html">Autoincrement Column</a> index. Your database table can define its primary key as Autoincrement number and MySQL will take care of its unique value while inserting new rows.</p><p>Each time you add a new row, MySQL increments the value automatically and persist it to table. But sometime you may want to reset the Autoincrement column value to 1. Say you writing a sample application and you have inserted few rows already in the table. Now you want to delete these rows and reset the autoincrement column to 1 so that new row which you insert will have primary key value 1.</p><p>There are few methods to achieve this.</p><h2>1. Directly Reset Autoincrement Value</h2><p>Alter table syntax provides a way to reset autoincrement column. Take a look at following example.</p><pre class="brush: sql; gutter: false; title: ; notranslate">
ALTER TABLE table_name AUTO_INCREMENT = 1;
</pre><p>Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.</p><h2>2. Truncate Table</h2><p>Truncate table automatically reset the Autoincrement values to 0.</p><pre class="brush: sql; gutter: false; title: ; notranslate">
TRUNCATE TABLE table_name;
</pre><p>Use this with caution. When Truncation is used, it resets any AUTO_INCREMENT counter to zero. From MySQL 5.0.13 on, the AUTO_INCREMENT counter is reset to zero by TRUNCATE TABLE, regardless of whether there is a foreign key constraint.</p><p>Once TRUNCATE is fired, the table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.</p><h2>3. Drop &#038; Recreate Table</h2><p>This is another way of reseting autoincrement index. Although not very desirable.</p><pre class="brush: sql; gutter: false; title: ; notranslate">
DROP TABLE table_name;
CREATE TABLE table_name { ... };
</pre><p>All these techniques are value techniques to reset autoincrement column number. Use whatever suits your requirement.</p><p><strong>Disclaimer:</strong> The above commands can delete all your data! Be very very cautious.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html" title="MySQL Database Backup using mysqldump command.">MySQL Database Backup using mysqldump command.</a></li><li><a href="http://viralpatel.net/blogs/2009/04/full-text-search-using-mysql-full-text-search-capabilities.html" title="Full-Text Search using MySQL: Full-Text Search Capabilities">Full-Text Search using MySQL: Full-Text Search Capabilities</a></li><li><a href="http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html" title="How to: Reset MySQL root password">How to: Reset MySQL root password</a></li><li><a href="http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html" title="Get Autoincrement value after INSERT query in MySQL">Get Autoincrement value after INSERT query in MySQL</a></li><li><a href="http://viralpatel.net/blogs/2008/11/mysql-change-root-password.html" title="MySQL Change root Password">MySQL Change root Password</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=OCBWqmW2p6o:1cN4zVoCOX8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=OCBWqmW2p6o:1cN4zVoCOX8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=OCBWqmW2p6o:1cN4zVoCOX8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=OCBWqmW2p6o:1cN4zVoCOX8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=OCBWqmW2p6o:1cN4zVoCOX8:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=OCBWqmW2p6o:1cN4zVoCOX8:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html</feedburner:origLink></item> <item><title>Struts 2 Tip: Override Default Theme</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/wrFBpzBxNcA/struts-2-override-default-theme.html</link> <comments>http://viralpatel.net/blogs/2011/12/struts-2-override-default-theme.html#comments</comments> <pubDate>Wed, 21 Dec 2011 12:07:40 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Struts 2]]></category> <category><![CDATA[Struts2]]></category> <category><![CDATA[struts2-series]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2465</guid> <description><![CDATA[Recently I came up with a requirement in Struts 2 to display a particular form with some style and alignment. While creating the form the developer had used Struts 2&#8242;s taglib /struts-tags to paint the user controls like textboxes and select boxes. For example: Now it turns of that Struts 2 parse these s: tags [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/8N25xDffEouIVeP7fzvHhsbdhfg/0/da"><img src="http://feedads.g.doubleclick.net/~a/8N25xDffEouIVeP7fzvHhsbdhfg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/8N25xDffEouIVeP7fzvHhsbdhfg/1/da"><img src="http://feedads.g.doubleclick.net/~a/8N25xDffEouIVeP7fzvHhsbdhfg/1/di" border="0" ismap="true"></img></a></p><p>Recently I came up with a requirement in Struts 2 to display a particular form with some style and alignment. While creating the form the developer had used Struts 2&#8242;s taglib <strong>/struts-tags</strong> to paint the user controls like textboxes and select boxes.</p><p>For example:</p><pre class="brush: xml; title: ; notranslate">
&lt;s:form action=&quot;add&quot; method=&quot;post&quot;&gt;
	&lt;s:textfield name=&quot;contact.firstName&quot; label=&quot;Firstname&quot;/&gt;
	&lt;s:textfield name=&quot;contact.lastName&quot; label=&quot;Lastname&quot;/&gt;
&lt;/s:form&gt;
</pre><p>Now it turns of that Struts 2 parse these <strong>s:</strong> tags and generate HTML tags like &lt;INPUT&gt; and &lt;SELECT&gt;. But Struts 2 not only generate these tags, but also generates enclosing &lt;TR&gt; tags to align them in a tabular format.</p><p>For example, the above Struts 2 code would generate HTML as following:</p><pre class="brush: xml; title: ; notranslate">
&lt;form id=&quot;add&quot; name=&quot;add&quot; action=&quot;add&quot; method=&quot;post&quot;&gt;
&lt;table class=&quot;wwFormTable&quot;&gt;
&lt;tr&gt;
    &lt;td class=&quot;tdLabel&quot;&gt;&lt;label for=&quot;add;contact_firstName&quot; class=&quot;label&quot;&gt;Firstname:&lt;/label&gt;&lt;/td&gt;
    &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;contact.firstName&quot; value=&quot;&quot; id=&quot;add;contact_firstName&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td class=&quot;tdLabel&quot;&gt;&lt;label for=&quot;add;contact_lastName&quot; class=&quot;label&quot;&gt;Lastname:&lt;/label&gt;&lt;/td&gt;
    &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;contact.lastName&quot; value=&quot;&quot; id=&quot;add;contact_lastName&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;
</pre><p>Note how Struts2 taglib generated enclosing TR tags around the controls. Lets see why this is so.</p><h2>Themes in Struts 2</h2><p>When you use a Struts 2 tag such as <code>s:select</code> in your web page, the Struts 2 framework generates HTML that styles the appearance and controls the layout of the select control. The style and layout is determined by which Struts 2 theme is set for the tag. Struts 2 comes with three built-in themes: <strong>simple, xhtml, and css_xhtml</strong>. If you don’t specify a theme, then Struts 2 will use the <strong>xhtml theme</strong> by default.</p><p>Thus in our case, Struts 2 automatically rendered the controls using default <em>xhtml</em> theme.</p><h2>Specifying The Theme in Struts 2</h2><p>The Struts 2 tags have a theme attribute you can use to specify which Struts 2 theme should be used when creating the HTML for that tag. The values for the theme attribute are simple, xhtml, css_xhtml, and ajax.</p><p>You can specify the theme on a per Struts 2 tag basis or you can use one of the following methods to specify what theme Struts 2 should use:</p><ul><li>The theme attribute on the specific tag</li><li>The theme attribute on a tag&#8217;s surrounding form tag</li><li>The page-scoped attribute named &#8220;theme&#8221;</li><li>The request-scoped attribute named &#8220;theme&#8221;</li><li>The session-scoped attribute named &#8220;theme&#8221;</li><li>The application-scoped attribute named &#8220;theme&#8221;</li><li>The <strong><code>struts.ui.theme</code></strong> property in struts.properties (defaults to xhtml)</li></ul><p>Thus, you can specify what theme you want to use at any level. Tag level, enclosed tag lever, form level, page level or at application level.</p><p>I preferred specifying theme at the application level. To override the default scheme you can create (or update existing) struts.properties file in your project.</p><p>Create struts.properties file and add following line into it:</p><p><em>File: struts.properties</em></p><pre class="brush: xml; gutter: false; title: ; notranslate">
struts.ui.theme = css_xhtml
</pre><p>So if you want to take full control for your user interface and want to align all controls yourself, I would suggest you to use <strong>css_xhtml</strong> theme instead of default xhtml.</p><p>The theme for above JSP code when changed into css_xhtml would generate following HTML code.</p><pre class="brush: xml; title: ; notranslate">
&lt;form id=&quot;add&quot; name=&quot;add&quot; action=&quot;add&quot; method=&quot;post&quot;&gt;
	&lt;div id=&quot;wwgrp_add_contact_firstName&quot; class=&quot;wwgrp&quot;&gt;
		&lt;div id=&quot;wwlbl_add_contact_firstName&quot; class=&quot;wwlbl&quot;&gt;
		&lt;label for=&quot;add_contact_firstName&quot; class=&quot;label&quot;&gt;Firstname:&lt;/label&gt;
		&lt;/div&gt;
		&lt;br /&gt;
		&lt;div id=&quot;wwctrl_add_contact_firstName&quot; class=&quot;wwctrl&quot;&gt;
		&lt;input type=&quot;text&quot; name=&quot;contact.firstName&quot; value=&quot;&quot; id=&quot;add_contact_firstName&quot;/&gt;
		&lt;/div&gt;
	&lt;/div&gt;
	&lt;div id=&quot;wwgrp_add_contact_lastName&quot; class=&quot;wwgrp&quot;&gt;
		&lt;div id=&quot;wwlbl_add_contact_lastName&quot; class=&quot;wwlbl&quot;&gt;
		&lt;label for=&quot;add_contact_lastName&quot; class=&quot;label&quot;&gt;Lastname:&lt;/label&gt;
		&lt;/div&gt;
		&lt;br /&gt;
		&lt;div id=&quot;wwctrl_add_contact_lastName&quot; class=&quot;wwctrl&quot;&gt;
		&lt;input type=&quot;text&quot; name=&quot;contact.lastName&quot; value=&quot;&quot; id=&quot;add_contact_lastName&quot;/&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/form&gt;
</pre><p>So all we have to do is to write CSS style for classes like wwgrp, wwlbl, wwctrl etc.</p><p>Hope this helps. Please comment if you have some specific requirement or suggestions.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate">Writing a URL Shortner in Java Struts2 &#038; Hibernate</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=wrFBpzBxNcA:_bdqsUoP3YE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=wrFBpzBxNcA:_bdqsUoP3YE:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=wrFBpzBxNcA:_bdqsUoP3YE:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=wrFBpzBxNcA:_bdqsUoP3YE:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=wrFBpzBxNcA:_bdqsUoP3YE:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=wrFBpzBxNcA:_bdqsUoP3YE:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/struts-2-override-default-theme.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2011/12/struts-2-override-default-theme.html</feedburner:origLink></item> </channel> </rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-01-27 14:14:07 -->

