Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Friday, December 28, 2012

Encode and Decode Example in Java

This post demonstrates the how to encode and decode the String data.

package com.ranga;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* This class is used to encode and decode the string data.
* @author Ranga Reddy
* @version 1.0
*/

public class EncodeAndDecodeExample {
private static final String data = "Hello, I am Ranga Reddy. ";

public static void main(String[] args) {

String encodedData = getEncodedData(data);
System.out.println("Encoded Data: " + encodedData);

String decodedData = getDecondedData(encodedData);
System.out.println("Decoded Data: " + decodedData);
}

private static String getDecondedData(String encodedData) {
try {
return URLDecoder.decode(encodedData, "UTF-8");
} catch (UnsupportedEncodingException exception) {
throw new RuntimeException("Does not support UTF-8");
}
}

private static String getEncodedData(String data) {
try {
return URLEncoder.encode(data, "UTF-8");

} catch (UnsupportedEncodingException exception) {
throw new RuntimeException("Does not support UTF-8");
}
}
}

Output:
Encoded Data: Hello%2C+I+am+Ranga+Reddy.+
Decoded Data: Hello, I am Ranga Reddy.

Saturday, October 27, 2012

Spring MVC Hello World Example

In this post, we are going to see how to implement Spring MVC HelloWorld example.
Step 1:
The initial step is to create Dynamic Web Project in eclipse. To create a new Dynamic project in Eclipse IDE select File -> Dynamic Web Project.
Step 2:
After that New Dynamic Project Window will appear on the screen and you will enter the web application name in the Project name text box. Enter SpringHelloWorld in the Project Name and then click Next button.

Step 3:
Add Spring Web MVC jar files.
spring-webmvc.jar
spring.jar
commons-logging.jar
Step 4:
Now we will created a index.jsp in project's WebContent  folder. In the jsp file we will create a new hyperlink "Click Here" that will be linked to hello.do page.  The code of index.jsp is:
index.jsp

<html>
<head>
<title>Spring Demo</title>
</head>
<body>
<a href="hello.do">Click Here</a>
</body>
</html>
Step 5:
Now we will configure the DispatcherServlet in web.xml file. The DispatcherServlet will be configured to process all the request ending with *.do
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringHelloWorld</display-name>
<description>Hello world Application</description>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 6:
Now we will create a new xml file called controller-servlet.xml in the WEB-INF folder of the web application. This is the main configuration file for the Spring MVC.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
Then we will define the url mapping with the Controller bean as shown below:

<property name="mappings">
<props>
<prop key="/hello.do">helloController</prop>
</props>
</property>
Finally we will define the Controller bean as shown below:
<bean id="helloController" class="com.ranga.HelloWorld"> </bean>
controller-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.do">helloController</prop>
</props>
</property>
</bean>
<bean id="helloController" class="com.ranga.HelloWorld" />
</beans>
Step 7:
After that we will creates the controller class in the project src folder. This will be used as the controller for the hello.jsp request. The code of the  HelloWorld.java calss is:

HelloWorld.java

package com.ranga;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloWorld implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
System.out.println("HelloWorld");
String str = "Hello World!";
return new ModelAndView("hello.jsp", "message", str);
}
}
Step 8:
After that we will create a hello.jsp in the WEB-INF folder. The WEB-INF/hello.jsp code is:
hello.jsp

<%@page isELIgnored="false" %>
${message}
Step 9:
To run the example select Run -> Run As -> Run On Server from the menu and then run the application on tomcat server. Eclipse will start Tomcat server and deploy the application on the Tomcat. Ellipse will also open the application in it internal browser as shown below:
Click on the "Click Here" link to test the application. It should display the "Hello World!" message as shown below.

Friday, October 19, 2012

Eclipse IDE Tutorial

Please find the following site(s) it is very useful for beginners and experienced people.

  • http://www.vogella.com/tutorials/Eclipse/article.html
  • https://www.eclipse.org/
  • http://www.tutorialspoint.com/eclipse/

Friday, September 14, 2012

Difficult Questions And Intelligent Answers for Interview

Difficult Questions and Intelligent Answers for Interview: 

1. How can you drop a raw egg onto a concrete floor without cracking it?
Ans. Concrete floors are very hard to crack! (UPSC Topper)

2. If it took eight men ten hours to build a wall, how long would it take four men to build it?
Ans. No time at all it is already built. (UPSC 23 Rank Opted for IFS)

3. If you had three apples and four oranges in one hand and four apples and three oranges in the other hand, what would you have?
Ans. Very large hands..(Good one) (UPSC 11 Rank Opted for IPS)

4. How can you lift an elephant with one hand?
Ans. It is not a problem, since you will never find! an elephant with one hand. (UPSC Rank 14 Opted for IES)

5. How can a man go eight days without sleep?
Ans. No Probs, He sleeps at night. (UPSC IAS Rank 98)

6. If you throw a red stone into the blue sea what it will become?
Ans. It will Wet or Sink as simple as that. (UPSC IAS Rank 2)

7. What looks like half apple?
Ans. The other half. (UPSC - IAS Topper)

8. What can you never eat for breakfast?
Ans. Dinner.

9. What happened when wheel was invented?
Ans. It caused a revolution.

10. Bay of Bengal is in which state?
Ans. Liquid (UPSC 33Rank)

11. How many buckets of water do Pacific Ocean contains?
Ans. It depends on the size of the bucket. (CA Institute Campus Interview Placement)

12. Interviewer said 'I shall either ask you ten easy questions or one really difficult question. Think well before you make up your mind!' The boy thought for a while and said, 'my choice is one really difficult question. ''Well, good luck to you, you have made your own choice! Now tell me this. 'What comes first, Day or Night?'
Ans. The boy was jolted into reality as his admission depends on his answer, but he thought for a while and said, 'It's the DAY sir!'
'How' the interviewer asked,
'Sorry sir, you promised me that you will not ask me a SECOND difficult question!'
He was selected for IIM!

Spliting a String without using any built in functions in Java

In this post, we are going to see how to split a string without using any built in functions.
package com.ranga;

import java.util.ArrayList;
import java.util.List;

/**
* Write a Java program to split a string with out using any bulit methods like
* split(), StringTokenizer class methods.
*
* @author Ranga Reddy
* @version 1.0
*/

public class SplitString {
public static void main(String[] args) {
String str = "Welcome to JavabyRangaReddy blog";
String delimiter = " "; // here delimiter is space
List<String> list = new ArrayList<String>(); // list is used to store the words
int i, start = 0, end = 0;
for (i = str.indexOf(delimiter); i != -1; i = str.indexOf(delimiter, i + 1)) {
end = i;
list.add(str.substring(start, end)); // by using substring we can get the one word
start = i;
}
list.add(str.substring(end)); // this is used to add the last word
System.out.println(list); // print the list

// Converting list to array of strings
String words[] = (String[]) list.toArray(new String[list.size()]);
for (String word : words) {
System.out.println(word.trim());
}
}
}
Output:
[Welcome,  to,  JavabyRangaReddy,  blog]
Welcome
to
JavabyRangaReddy
blog

Thursday, September 13, 2012

JAVA IDE's

Best JAVA IDE :

Integrated Development Environments (IDE) provide benefits to programmers that plain text editors cannot match. IDEs can parse source code as it is typed, giving it a syntactic understanding of the code. This allows advanced features like code generators, auto-completion, refactoring, and debuggers. Here are the best-of-breed Java IDEs.

1) Eclipse :

Price: Free
License: Open Source (CPL)
Summary: Eclipse is a free IDE that has taken the Java industry by storm. Built on a plugin architecture, Eclipse is highly extensible and customizable. Third-party vendors have embraced Eclipse and are increasingly providing Eclipse integration. Eclipse is built on its own SWT GUI library. Eclipse excels at refactoring, J2EE support, and plugin support. The only current weakness of Eclipse is its lack of a Swing or SWT GUI designer.
The eclipse platform provides tool developers with ultimate flexibility and control over their software technology.
Likes:
  • IDE looks amazing, across all systems, and it is quite responsive...great interface overall!
  • anti-aliased text everywhere, even in UI!
  • ability to format to your line wrapping width.
  • refactoring support ascends from heaven!
  • easy to share code between projects
  • ant integration very well done, ant launcher makes managing project tree very easy.
  • content assist is used whereever possible, not just in editor (wizards scrrens).
  • amazing control over the formatting of java source code, which can be saved as a profile.
  • pasting code formats code automatically!
  • editor tabs can be moved around with drag-and-drop.
  • can double-click editor tabs to expand to full workspace view.
  • has both docked views and fast views (most editors only offer one or the other).
  • very powerful control over how the java compiler handles warnings and errors.
  • very small project-specific footprint on directory tree (.project, .classpath).
  • package view has very nice filtering abilities, for what to show/not show (can now filter closed packages, selected working set).
  • code assist in ant resolves location properties and displayes the path in a tooltip!!
  • code assist shows documentation for each option, especially helpful for ant tasks.
  • awesome integrated diff engine and viewer for comparing files and refactoring changes.
  • can rearrange the order of properties and methods in the "outline" view.
  • context aware templates, tab/shift-tab to jump to different insertion points (markers).
Dislikes :
  • editor does not have a split file view!!
  • lacks general syntax highlighting out of the box (property file highlighting added in 3.1).
  • no "soft" line wrapping (only hard wrapping by issuing the format command).
  • doesn't come with native servlet/J2EE aware plugins (you have to configure a plugin, such as lomboz, webtools or myeclipse).
  • must manually create ant scripts, though the code assist support is very well done.
  • cannot create new buffer without creating linked file (annoyance, fixed in 3.1).
  • double clicking on file in package explorer does not close editor if it is currently open (JEdit feature).
2) Netbeans 3 (Sun Microsystems):
Price: Free
License: Open Source (CPL)
Summary: Netbeans is a free IDE backed by Sun Microsystems. It is the main competitor of Eclipse. Netbeans is built on a plugin architecture, and it has respectable third-party vendor support. The main advantage of Netbeans over Eclipse is Netbean's excellent GUI designer. It includes syntax highlighting and language support for Java, JSP, XML/XHTML, visual design tools, code generators, ant and CVS support.
(Free) and derivatives like SunJavaStudio? (Commercial) and Compuware OptimalJ? (Commercial).
Likes:
  • very nice code completion engine, never seems too aggressive, very thorough in what it includes, esp jsp.
  • code formatting/reindent task (located in context menu), especially nice for XML/XHTML.
  • creating custom tag libraries was very easy, step by step process straightforward (once I knew where to look).
  • very nice integration with Tomcat, no setup required, direct pages testing, spawns browser, always updates correctly.
  • can specify default request parameters when testing a page.
  • view generated source code for jsp.
  • the whole Tomcat integration module is superb!.
  • nice jsp tag repository support in jsp editor, very easy to add tag libraries to jsp page.
  • HTTP monitor integration very nice, again, part of integration with servlet engine, A++.
  • can move around tabs, I love this (tabs also don't wrap to next line, big plus).
  • validate JSP is very helpful and quite informative...tells you exactly what is missing.
  • javadoc wizard could come in handy, definitely a cool feature, more than just a GUI.
  • method/field navigator as a select box is a nice idea on main UI, don't take up space.
  • can move around all views, group as tabs, etc...easy to customize placements, but doesn't get too complicated like with "workspaces" in eclipse.
  • block indenting/unindenting function, great for XML/XHTML (hardly need it with the code reformatting).
  • very responsive and quick UI.
  • anti-aliased text in editor.
  • very acceptable IDE layout.
  • can right-click file and "Save as template..." which is especially nice for JSP content pages
  • very nice database browser, manipulator, easy to setup.
Dislikes:
  • UI looks crappy (metal), icons suck.
  • no refactoring or refactoring templates (try/catch, rename field, etc...).
  • no JSTL-EL support in syntax highlighting/code completion.
  • cannot wrap arbitrary text in editor.
  • wierd issues with "mounting" core libraries, causes errors and features not to work correctly, such as code completion...the whole "mounting" thing is very strange.
  • new file wizards too minimial.
  • limited control over formatting of java source code (though the defaults won't kill you and it can reformat nicely).
  • Very difficult (for newbies impossible) to add a regular ol' jar file to a project. Every mechanism seems to work against you.
  • Cannot import sources from somewhere else into project, rather you can only mount them where they are...need a copy mechanism.

3) IntelliJ IDEA :

Price: $499
License: Proprietary
Summary : IntelliJ IDEA is a commercial IDE with a loyal following that swear by it. It has excellent J2EE and GUI support. It is extensible via plugins. Its standout feature is the outstanding refactoring support.
It provides a robust combination of enhanced development tools, including: refactoring, J2EE support, Ant, JUnit, and CVS integration. Packaged with an intelligent Java editor, coding assistance and advanced code automation tools, IDEA enables Java programmers to boost their productivity while reducing routine time consuming tasks.
Likes :
  • Superb block editing, the best I have seen, has a distinct "column mode" setting which can be toggled in the context menu.
  • refactoring works flawlessly, has a nice preview, doesn't hose project.
  • Excellent keymapping support, going so far as to support key sequences ala emacs.
  • Interesting support for anywhere editing (automatically places spaces to fill).
  • Once tld is accessible (in classpath), instant tag support in JSP, no need to "assign" it to the IDE.
  • once setup, tomcat integrate is very streamlined, offers a "dump threads" utility for a sudo-reload, JSPs recompile after save.
  • project view is very simple, easy to understand...arranging projects is user-friendly and intuitive.
  • best looking theme next to Eclipse (even on Linux), limited only by java and fonts.
  • anti-aliased text in editor, also in docked tabs.
  • Struts Console plugin offers great Struts config and tld file support.
  • very nice integrated class browser whenever a class is required for input.
  • keymap hints in UI menus update to reflect current keymappings, not just the default set.
  • ant view allows for filtering of targets using a pick list (great for huge build files).
Dislikes :
  • deployment server must be setup separately.
  • No "X" button on editor tabs to close a file, must right click or use keymapping.

4) JBuilder X (Borland) :

Price: $499 (JBuilder 2007)
License: Proprietary
Summary: Jbuilder has long been the top commercial Java IDE. It is an excellent IDE, but it is not built to be open and extensible by third-part vendors. They have a free version but moving up from the free version gets expensive. JBuilder is a complete Java IDE for EJB, Web and Web Services, offering integration with application servers (namely BEA Weblogic), a Struts designer, unit testing, refactoring and support for several source control systems.
Likes :
  • Code template expansions are very helpful, prevents redundant typing (expand with CTRL-J).
  • Can view images in separate tab.
  • Archive builder offers a nice wizard replacement for many ant tasks.
  • Decent built-in database plugin for managing and querying a SQL database.
  • Built-in makefile task for build, clean, rebuild, no need to create ant script.
  • sound effects are a nice touch.
  • JSTL-EL syntax highlighting support.
  • antialiased text editor.
  • can make edit window full screen by double clicking tab.
Dislikes :
  • EXPENSIVE!
  • options in hard to find places.
  • cannot reformat non-java code, such as XML/XHTML.
  • renaming a project is a recipie for disaster, everything gets screwed (most crucially the paths)!
  • recompiling with an active "web run" will sometimes redeploy, sometimes won't redeploy; it's completely random, so you constantly have to restart the weblogic server.
  • refactoring is crap, even renaming a field screws up the code; possible to hose your project in untold ways by renaming things.
  • adding fields to class doesn't allow specification of access (private|protected|public).
  • cannot delete a directory or a package in a project.
  • jsp validation is not very helpful, just tells you on what line an error occurs.
  • wizard for "implement interface" but no wizard for "extend class".
  • when creating new files, you get a different create screen depending on where you selected the option, CONFUSING!!.
  • no syntax highlighting for java properties files, and no editor.
  • many times the error insight will detect an error, but it won't tell you what the error is until you try to compile.
  • multiple projects can not be viewed at once, must repeatedly toggle which project is displayed.

5) JDeveloper (Oracle) :

Price: Free {$218.90 per named user plus per year For Support}
License: Proprietary
Summary: Oracle JDeveloper is an integrated development environment with end-to-end support for modeling, developing, debugging, optimizing, and deploying Java applications and Web services. Oracle JDeveloper 10g introduces a new approach to J2EE development with features that enable visual and declarative development. The innovative OAF simplifies J2EE development.
Likes:
  • very nice integration with embedded OC4J container, very easy to execute test page, updates reflected immediately.
  • browser launcher is configurable (good for tabbed browsing and multiple launches).
  • JSP engine and code editor is the best I have seen, super easy to work with, delightful!
  • code insight for EL expressions!
  • auto insert of taglib uri directive when inserting a taglib in JSP page source.
  • several ways to do block indent formatting (highlight block and tab/shift-tab will indent/unindent).
  • very nice forms for creating all aspects of classes.
  • very nice forms for creating classes from *.tld files and keeping the two in-sync/connected.
  • adding taglibs to a project is somewhat intuitive...if you know what to press, it works just fine.
  • message windows informative on build.
  • deployment descriptors have previews so you know what they are going to encapsulate.
  • nice refactoring support.
  • code template support.
  • the timeout on most "auto" aspects can be configured to happen after a time interval, configured with a slider bar...nice concept!
  • Nice import mechanism for sources, very comprehensive wizard
Dislikes:
  • old stuff tends to hang around, constant have issues with "artifacts" of a project, no "make clean".
  • files can get really messed up if you don't remove them properly from disk...learn the order of doing things and stick with it.
  • no clear way to remove a class altogether, if created by accident (I found it, located in file, NOT intuitive).
  • no way to rename a *.tld file once it is created with wizard.
    somewhat slow, not quite as quick as netbeans.
  • several places where a class or interface is required that you have to do manual typing, no integrated class browser.
  • look and feel is descent, some descent icons.
  • cannot maximize a tab to take up the whole window.
  • no way to make textarea anti-aliased text.
  • doesn't remember last openned directory...argh!!

6) SlickEdit :

Price: $284 for a named user license
License: Proprietary
Summary : SlickEdit is an old greybeard in the IDE space. This powerful commercial IDE is a favorite of developers who must switch between several languages. It is a full-featured IDE in dozens of languages, including Java, C++, C#, and HTML. SlickEdit comes as a standalone application or as a plugin for Eclipse.
Likes:
  • SlickEdit is easy to install and configure.
  • large number of supported platforms.
  • As a coding editor SlickEdit has the usual features one would expect from any professional environment - code completion, syntax highlighting and so on.
  • Best feature of SlickEdit is the ability to customise it, to shape the application to fit your own way of working.
  • When creating a new Java class the editor automatically creates the required directories for the specified package—you don't have to specify the package and class names. This feature adds to SlickEdit's productivity.
  • SlickEdit comes with a powerful debugger that you can use to run Java applications in debug mode and step through the code.
  • This tool also provides a very good interface to write and execute JUnit test scripts from within the editor which will be a great help for those who follow TDD-based application development.
  • One cool thing about SlickEdit is that it provides several code templates you can use to add new features to your workspace. You can also add your own templates (much like custom plug-ins in Eclipse).
Dislike:
  • Customizability however, comes with the downside that the application is at first use quite difficult to get into and use.
  • It would be nice if the tool had an option to auto-generate getter and setter methods for the attributes defined in a Java class.

7) jEdit :

Price: open source
License: Proprietary
Summary : jEdit is a free, mature, and well-designed programmer's code editor that is written in Java and is highly customizable through plugins and options. This editor is sufficiently powerful to be considered a professional strength IDE.
Like:
  • it's a fine example of a Java desktop tool that looks good, is packed full of useful functionality and has snappy response times.
  • Dozens of macros and plug-ins available.
Dislike:
  • In terms of features not comparable to eclipse or visual studio.

8) JCreater :

Price: Free
License: Proprietary
IDE from Xinox. JCreator has two editions: JCreator Pro (free 30 day trial), JCreator Standard (completely free). Note also that unlike many other Java IDEs, this one is not coded in Java but is written in C++ and optimised for the Windows platform.
Like:
  • a small download compared to some of the better known Java IDEs.
  • There is some automation in terms of wizards for new workspaces, projects, classes and interfaces.
  • The environment features a some level of configurability, with tool bars, key bindings and links to external tools all available.
  • If you develop on Windows and are looking for something that's fast and light-weight then this is one tool that deserves serious consideration.
Dislike :
  • JCreator runs under Windows, there's no Linux or Unix version.
  • Lack of an effective macro or plug-in architecture means that extending with new functionality is not an option.
  • JCreator clearly doesn't have the full range of functionality that the big platforms - Eclipse and NetBeans - have to offer.

9) IBM WebSphere Studio Site Developer for Java :

Java IDE for Windows and Linux. Expensive but very powerful IDE for servlets, JSP, and other J2EE development. Not limited to use with the WebSphere app server.

10) WebLogic Workshop:

BEA WebLogic Workshop is a very powerful IDE for developing applications on the BEA Web Logic Server. Weblogic workshop runs on Windows, Linux and Solaris and requires a Weblogic Servier. We can download a free version or a professional version.

Wednesday, August 1, 2012

AJAX Drop down Example with Database

The following are the steps for creating a dropdown list by using ajax with database.

1. Create Dynamic Web Project : Open File -> New -> Other... -> Web -> Dynamic Web Project to create a dynamic Web project.
  1. Click Next .
  2. Enter the name of the Web project into the Project Name field.
  3. Proceed to one of the following steps:
    • No server runtime installed.
      • If you have not previously configured a server runtime, use the New... button beside the Target runtime field to do so.
      • Proceed to next step depending on whether target runtime is automatically selected.
    • Target runtime automatically selected
      • If you had previously installed a Tomcat 5.0 server runtime and the workbench default JRE is set to JRE 1.4, then the Target runtime field should be automatically set to Apache Tomcat v5.0 .
2.  Create a database tables and inserting values :

SHOW DATABASES;

USE `test`;

CREATE TABLE `country` ( `countryid` BIGINT(255) NOT NULL AUTO_INCREMENT, `countryname` VARCHAR(255) DEFAULT NULLPRIMARY KEY (`countryid`) ) ;

CREATE TABLE `state` ( `stateid` BIGINT(255) NOT NULL AUTO_INCREMENT, `countryid` INT(255) DEFAULT NULL, `state` VARCHAR(255) DEFAULT NULLPRIMARY KEY (`stateid`) ) ;

CREATE TABLE `city`( `cityid` BIGINT(255) NOT NULL AUTO_INCREMENT, `stateid` INT(255) DEFAULT NULL,`city` VARCHAR(255) DEFAULT NULLPRIMARY KEY (`cityid`));

INSERT INTO `test`.`country` (`countryid`, `countryname`) VALUES ('1''india');
INSERT INTO `test`.`country` (`countryid`, `countryname`) VALUES ('2''sri-lanka');
INSERT INTO `test`.`country` (`countryid`, `countryname`) VALUES (NULL'america');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'1''andhrapradesh');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'1''karnataka');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'1''tamilnadu');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'1''kerala');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'1''arunachal pradesh');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'2''Colombo');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'2''Kandy');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'2''Bandarawela');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'3''California');
INSERT INTO `test`.`state` (`stateid`, `countryid`, `state`) VALUES (NULL'3''Georgia');
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'1'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'1'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'1'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'1'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'2'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'2'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'2'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'2'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'2'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'2'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'3'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'3'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'3'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'4'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'4'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'4'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'4'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'5'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'5'NULL); 
INSERT INTO `test`.`city` (`cityid`, `stateid`, `city`) VALUES (NULL'5'NULL); 
UPDATE `test`.`city` SET `city` = 'chittoor' WHERE `cityid` = '1';
UPDATE `test`.`city` SET `city` = 'anantapur' WHERE `cityid` = '2';
UPDATE `test`.`city` SET `city` = 'kurnool' WHERE `cityid` = '3';
UPDATE `test`.`city` SET `city` = 'nellore' WHERE `cityid` = '4';
UPDATE `test`.`city` SET `city` = 'bangalore' WHERE `cityid` = '5';
UPDATE `test`.`city` SET `city` = 'mangalore' WHERE `cityid` = '6';
UPDATE `test`.`city` SET `city` = 'udipi' WHERE `cityid` = '7';
UPDATE `test`.`city` SET `city` = 'ballari' WHERE `cityid` = '8';
UPDATE `test`.`city` SET `city` = 'mysore' WHERE `cityid` = '9';
UPDATE `test`.`city` SET `city` = 'darmastalam' WHERE `cityid` = '10';
UPDATE `test`.`city` SET `city` = 'chennai' WHERE `cityid` = '11';
UPDATE `test`.`city` SET `city` = 'Coimbatore' WHERE `cityid` = '12';
UPDATE `test`.`city` SET `city` = 'Erode' WHERE `cityid` = '14';
UPDATE `test`.`city` SET `city` = 'Erode' WHERE `cityid` = '13';
UPDATE `test`.`city` SET `city` = 'kannor' WHERE `cityid` = '14';
UPDATE `test`.`city` SET `city` = 'kasrgood' WHERE `cityid` = '15';
UPDATE `test`.`city` SET `city` = 'thrisoor' WHERE `cityid` = '16';
UPDATE `test`.`city` SET `city` = 'kollam' WHERE `cityid` = '17';
UPDATE `test`.`city` SET `city` = 'tirap' WHERE `cityid` = '18';
UPDATE `test`.`city` SET `city` = 'siang' WHERE `cityid` = '19';

3. Create a Jsp pages



country.jsp


<%@page import="java.sql.*"%>

 <html>
      <head> 
            <script type="text/javascript"> 
            var xmlHttp;
            var xmlHttp;
            function showState(str){
                  if (typeof XMLHttpRequest != "undefined"){
                  xmlHttp= newXMLHttpRequest();
            }
            else if(window.ActiveXObject){
                     xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xmlHttp==null){
                  alert("Browser does not support XMLHTTP Request")
                  return;
            }
            var url="state.jsp";
            url +="?count=" +str;
            xmlHttp.onreadystatechange = stateChange;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
            }
     
            functionstateChange(){  
                  if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {  
                  document.getElementById("state").innerHTML=xmlHttp.responseText   
                  }  
                }
           
            function showCity(str){
            if (typeof XMLHttpRequest != "undefined"){
              xmlHttp= newXMLHttpRequest();
              }
            else if(window.ActiveXObject){
              xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
              }
            if (xmlHttp==null){
            alert("Browser does not support XMLHTTP Request")
            return;
            }
                  var url="city.jsp";
                  url +="?count=" +str;
                  xmlHttp.onreadystatechange = stateChange1;
                  xmlHttp.open("GET", url, true);
                  xmlHttp.send(null);
            }
            functionstateChange1(){  
                  if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){  
                        document.getElementById("city").innerHTML=xmlHttp.responseText   
                  }  
            }
            </script> 
      </head> 
      <body> 
      <br/>
      Country : <select name='country'onchange="showState(this.value)"> 
       <option value="none">Select Country</option> 
          <%
                  Class.forName("com.mysql.jdbc.Driver").newInstance(); 
                  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); 
                  Statement stmt = con.createStatement(); 
                  ResultSet rs = stmt.executeQuery("Select * from country");
                  while(rs.next()){
            %>
                  <option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option> 
            <%
                  }
            %>
      </select> 
      <br> 
      <div id='state'> 
            State :  <selectname='state' > 
                  <option value='-1'>Select State</option> 
            </select> 
      </div> 

      <div id='city'> 
           City : <select name='city' > 
                  <option value='-1'>Select District</option> 
            </select> 
      </div>
      </body>
</html>

state.jsp
<%@page import="java.sql.*"%>
<%
      String country=request.getParameter("count"); 
      String buffer="State : <select name='state' onchange='showCity(this.value);'><option value='-1'>Select</option>"
      try{
            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); 
            Statement stmt = con.createStatement(); 
            ResultSet rs = stmt.executeQuery("Select * from state where countryid='"+country+"' "); 
            while(rs.next()){
            buffer=buffer+"<option value='"+rs.getString(1)+"'>"+rs.getString(3)+"</option>"
            } 
            buffer=buffer+"</select>"
            response.getWriter().println(buffer);
      }
      catch(Exception e){
            System.out.println(e);
      }
%>

city.jsp
<%@page import="java.sql.*"%>
<%
      String state=request.getParameter("count"); 
      String buffer="City : <select name='city'><option value='-1'>Select</option>"
      try{
            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); 
            Statement stmt = con.createStatement(); 
            ResultSet rs = stmt.executeQuery("Select * from city where stateid='"+state+"' "); 
            while(rs.next()){
            buffer=buffer+"<option value='"+rs.getString(2)+"'>"+rs.getString(3)+"</option>"
            } 
            buffer=buffer+"</select>"
            response.getWriter().println(buffer);
      }
      catch(Exception e){
            System.out.println(e);
      }
%>

Output:


Run the country.jsp

 Select the country

 Select the state
 Select the city