Wednesday, December 18, 2013

Image Upload

index.jsp

<form name="form" onSubmit='return validate();' action="change_photo.do" method="post" enctype="multipart/form-data">
                        <span style="padding-left: 30px">Upload Picture : <input type ="file"  id="fileChooser"  name="pic" style="margin-left: 23px"/></span><br /><br/>
                        <span class="submit" ><input type="submit" value="Change Photo" name="submit"/></span>
                    </form>

validation


<script type="text/javascript">
            function validate()
{
var extensions = new Array("jpg","png");
var pic = document.form.pic.value;
var image_length = document.form.pic.value.length;
var pos = pic.lastIndexOf('.') + 1;
var ext = pic.substring(pos, image_length);
var final_ext = ext.toLowerCase();


for (i = 0; i < extensions.length; i++)
{
        if(extensions[i] == final_ext)
        {
           
        if(val()){
        return true;
        }
        }
}
alert("You must upload file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}

        </script>



change_photo.java



package com;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DbConnection;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 * @version 1.0
 * @author www.codejava.net
 */
public class change_photo extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "upload";
    private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024; // 4MB
    private static final int REQUEST_SIZE = 1024 * 1024 * 1; // 5MB

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            DbConnection dbc=new DbConnection();
            Connection con=dbc.getCon();
            Statement st=null;
            ResultSet rs=null;
            PreparedStatement pst=null;
            String finalImg="";
            String value="";
            String value1="";
            HttpSession hs=request.getSession();
            String id=(String)hs.getAttribute("id");
            st=con.createStatement();         
            // checks if the request actually contains upload file
            if (!ServletFileUpload.isMultipartContent(request)) {
                // if not, we stop here
                return;
            }
            
            // configures some settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(THRESHOLD_SIZE);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
            
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(REQUEST_SIZE);
            
            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("")
                + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
             System.out.print("file is there");
            ArrayList<String> ll=new ArrayList<String>();
            try
            {
                // parses the request's content to extract file data
                List formItems = upload.parseRequest(request);
                int s=formItems.size();
                for(int i=0;i<1;i++)
                {
                                Iterator iter = formItems.iterator();

                                // iterates over form's fields

                                while (iter.hasNext())
                                {
                                    FileItem item = (FileItem) iter.next();
                                    // processes only fields that are not form fields
                                    if (!item.isFormField())
                                    {
                                        String fileName = item.getName();
                                        Random gen = new Random();
                                            int r = Math.abs(gen.nextInt());

                                            String reg = "[.*]";
                                            String replaceText = "";
                                            String finalname=fileName;
                                           
                                            System.out.print(finalname);
                                            //System.out.println("Text before replacing is: " + fileName);
                                            Pattern pattern = Pattern.compile(reg);
                                            Matcher matcher = pattern.matcher(fileName);

                                            StringBuffer buffer = new StringBuffer();
                                            while(matcher.find())
                                            {
                                                matcher.appendReplacement(buffer, replaceText);
                                            }
                                            int indexOf = fileName.indexOf(".");
                                            String domainName = fileName.substring(indexOf);
                                            //System.out.println("Domain Name: "+ domainName);
                                            //System.out.print(buffer.toString());
                                            finalImg = buffer.toString()+r+i+domainName;
                                            ll.add(finalImg);

                                            System.out.println("Final Image: "+ finalImg);




                                        String filePath = uploadPath +  File.separator + finalImg;
                                        File storeFile = new File(filePath);
                                        //System.out.print(filePath);
                                        // saves the file on disk
                                        item.write(storeFile);
                                      
                                   
                                }
                  
                                   
                                   

                   
                   
                                 
                }
            }
              
                    String sql="UPDATE `tbl_employee` SET `pic`=? WHERE id=?";
                    pst=con.prepareStatement(sql);
               
                    Iterator<String> iter=ll.iterator();
                   
                    for(int i=1;iter.hasNext();i++)
                    {
                        String name=iter.next();
                        pst.setString(i,name);
                    }
                    pst.setString(2, id);
                   
                   
                   
                    int i=pst.executeUpdate();
               
                System.out.print("inserted" +i);
                request.setAttribute("message", "Upload has been done successfully!");
            }
            catch (SQLException ex) {
                 request.setAttribute("message", "Something Went Wrong.");
            }
           
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: Size Of photo must be less than (1 MB)");
        }
        getServletContext().getRequestDispatcher("/ChangePic.jsp").forward(request, response);
    }
}

Usebean jsp

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <form action ="test.do">
    <body>
       Enter Name:
       <input type="text" name ="name"></input>
       <br>
       Enter Dog Name:
       <input type="text" name ="dname"></input>
       <input type="submit" value="Submit" />
    </body>
    </form>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <jsp:useBean id="person" scope="request" class="bean.Person">
            <jsp:setProperty name="person" property="name" param="name"></jsp:setProperty>
            <jsp:setProperty name="person" property="dname" param="dname"></jsp:setProperty>
        </jsp:useBean> 
        Name created by servlet: <jsp:getProperty name="person" property="name"></jsp:getProperty>
        <br>
        Dog Name is:
        ${person.dname}

</body>
</html>

test.do

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String dname = request.getParameter("dname");
       
        Person p=new Person();
        p.setName(name);
        p.setDname(dname);
        request.setAttribute("person", p);
        RequestDispatcher rd = request.getRequestDispatcher("result.jsp");
        rd.forward(request, response);
    }

Person.jsp

package bean;

public class Person {
String name,dname;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDname() {
    return dname;
}

public void setDname(String dname) {
    this.dname = dname;
}


}


Struts Crude

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Registration</title>
</head>
<body>

<s:form action="addUser">
    <s:textfield name="user.userName" label="User Name" />
    <s:password name="user.password" label="Password" />
    <s:textfield name="user.email" label="email"/>
   
    <s:submit name="submit" value="Add User" />   
</s:form>
<br />
<s:a href="listUser.action">Show List of Users</s:a>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>StrutsDataBase</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>strtus2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>strtus2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

struts.xml

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.ognl.allowStaticMethodAccess" value="false" />

    <package name="default" extends="struts-default">
        <action name="addUser" class="com.action.struts.Registration" method="addUser">
            <result name="success" type="redirect">listUser.action</result>
            <result name="input">/index.jsp</result>
        </action>
        <action name="updateUser" class="com.action.struts.Registration" method="updateUser">
            <result name="success" type="redirect">listUser.action</result>
            <result name="input">/edituser.jsp</result>
        </action>
        <action name="editUser" class="com.action.struts.Registration" method="editUser">
            <result name="success">edituser.jsp</result>
        </action>
        <action name="deleteUser" class="com.action.struts.Registration" method="deleteUser">
            <result name="success" type="redirect">listUser.action</result>
        </action>
        <action name="listUser" class="com.action.struts.Registration" method="listUser">
            <result name="success">/showuser.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>
 
showuser.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show List of Users</title>
</head>
<body>
<a href="index.jsp">Add User</a>

<s:if test="users.size() > 0"></s:if>
    <table>
        <tr>
            <th>ID</th>
            <th>USER NAME</th>
            <th>PASSWORD</th>
            <th>EMAIL</th>
            <th>UPDATE</th>
            <th>DELETE</th>
        </tr>  
   
<s:iterator value="users" >
    <tr>
        <td><s:property value="%{userId}"/></td>
        <td><s:property value="%{userName}"/></td>
        <td><s:property value="%{password}"/></td>
        <td><s:property value="%{email}"/></td>
        <td>
            <s:url id="editURL" action="editUser">
                <s:param name="user.userId" value="%{userId}"></s:param>
            </s:url>
            <s:a href="%{editURL}">Edit</s:a>
        </td>
        <td>
            <s:url id="deleteURL" action="deleteUser">
                <s:param name="user.userId" value="%{userId}"></s:param>
            </s:url>
            <s:a href="%{deleteURL}">Delete</s:a>
        </td>
    </tr>
</s:iterator>
</table>
</body>
</html>

editUser.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="updateUser">
    <s:hidden name="user.userId"/>
    <s:textfield name="user.userName" label="User Name" />
    <s:textfield name="user.password" label="Password"  />
    <s:textfield name="user.email" label="email"/>
   
    <s:submit name="submit" value="Update User" />   
</s:form>
<s:url id="showUser" action="listUser"></s:url>
<s:a href="%{showUser}">Back</s:a>
</body>
</html>

com.action.struts.Registration

package com.action.struts;
import java.util.ArrayList;
import java.util.List;

import com.bean.User;
import com.impl.UserImpl;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.net.httpserver.Authenticator.Success;

public class Registration extends ActionSupport {

   
    private User user;
    private List<User> users = new ArrayList<User>();
       
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
   
    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return SUCCESS;
    }
   
    public String addUser(){
       
        UserImpl.addUser(user);
               
        return SUCCESS;
    }
   
    public String listUser(){
       
        users =UserImpl.listUser();
       
        return SUCCESS;
    }
   
    public String deleteUser(){
       
        UserImpl.deleteUser(user);
       
        return SUCCESS;
    }
   
    public String editUser(){
       
        user = UserImpl.findUser(user);
       
        return SUCCESS;
    }
   
    public String updateUser(){
        /*HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        user = userDAO.listUserById(Long.parseLong(request.getParameter("id")));*/
        UserImpl.updateUser(user);
       
        return SUCCESS;
    }
   
   
   
}

com.bean.User

package com.bean;

public class User {

    private int userId;
    private String userName;
    private String password;
    private String email;
       
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
   
}

com.dao.Dbconnector

package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnector {

    public static Connection getConnection(){
       
        Connection con= null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        return con;
    }
   
}

com.Impl.UserImpl

package com.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.bean.User;
import com.dao.DBConnector;

public class UserImpl {

   
    public static void addUser(User user){
       
        try {
            Connection con = DBConnector.getConnection();
            Statement st = con.createStatement();
           
            String sql = "insert into tbl_demo (useremail,username,password) values('"+user.getEmail()+"', '"+user.getUserName()+"', '"+user.getPassword()+"')";
            int query = st.executeUpdate(sql);
            System.out.println(query);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
   
    }
   
    public static List<User> listUser(){
       
        List<User> users= new ArrayList<>();
        try {
            Connection con = DBConnector.getConnection();
            Statement st = con.createStatement();
           
            String sql = "select * from tbl_demo";
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()){
                User user = new User();
                user.setUserId(rs.getInt(1));
                user.setEmail(rs.getString(2));
                user.setUserName(rs.getString(3));
                user.setPassword(rs.getString(4));
                users.add(user);
            }
           
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return users;
       
    }
   
    public static void deleteUser(User user){
        try {
            Connection con = DBConnector.getConnection();
            Statement st = con.createStatement();
           
            String sql = "delete from tbl_demo where id="+user.getUserId();
            int query = st.executeUpdate(sql);
            System.out.println(query);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
    public static User findUser(User user){
        try {
            Connection con = DBConnector.getConnection();
            Statement st = con.createStatement();
           
            String sql = "select * from tbl_demo where id="+user.getUserId();
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()){
            user.setUserId(rs.getInt(1));
            user.setEmail(rs.getString(2));
            user.setUserName(rs.getString(3));
            user.setPassword(rs.getString(4));
            }
           
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        return user;
    }
   
    public static void updateUser(User user){
        try {
            Connection con = DBConnector.getConnection();
            Statement st = con.createStatement();
           
            String sql = "update tbl_demo  set useremail ='"+user.getEmail()+"', username = '"+user.getUserName()+"',password = '"+user.getPassword()+"' where id="+user.getUserId();
            int query = st.executeUpdate(sql);
            System.out.println(query);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
   
}

Insert through JSTL

index.jsp

<form method="POST" action="insertLocations.jsp">
                        <label> Country : </label> <input type="text" name="country" id="country" /><br/><br/>
                        <label> State : </label> <input type="text" name="state" id="state" /><br/><br/>
                        <label> City :  <input type="text" name="city" id="city" /><br/><br/>
                        <span class="submit"><input type="submit" name="Add" value="Add Location" /></span>
</form>

insertLocations.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<c:import url="include/connection.jsp"></c:import>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<c:import url="include/connection.jsp"></c:import>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    </head>
    <body>
       <c:if test="${pageContext.request.method=='POST'}" >
           <c:catch var="exception">
           <c:if test="${empty param.country or empty param.state or empty param.city}">
               <c:redirect url="addLocations.jsp?message">
                   <c:param name="message"  value="Please fill all details."> </c:param>
               </c:redirect>
           </c:if>
          
           <sql:query var="database" dataSource="${ds}">
                   select count(*) as kount  from tbl_locations where `country`='${param.country}' && `state`='${param.state}' &&`city`='${param.city}'
           </sql:query>
            <c:forEach items="${database.rows}" var="r">
            <c:choose>
                <c:when test="${r.kount gt 0}">
                    <c:redirect url="addLocations.jsp?message=Location Already exists."></c:redirect>
                </c:when>
           </c:choose>
           
            </c:forEach>                  
                  
          
          
       <sql:update var="insert_loc" dataSource="${ds}" >
           insert into tbl_locations (`country`,`state`,`city`) values (?,?,?)
           <sql:param value="${param.country}"></sql:param>
           <sql:param value="${param.state}"></sql:param>
           <sql:param value="${param.city}"></sql:param>          
       </sql:update>
         
           <c:if test="${insert_loc>0}">
               <c:redirect url="addLocations.jsp">
                   <c:param name="message" value="Location added succesfully."></c:param>
               </c:redirect>
           </c:if>
           </c:catch>
           <c:if test="${not empty exception}">
               <c:redirect url="addLocations.jsp">
                   <c:param name="message" value="Something went wrong."></c:param>
               </c:redirect>
            </c:if>
       </c:if>
    </body>
</html>
 

Login through JSTL

index.jsp

<div style="height:200px;width:350px;margin: 25px 0px 0px 23px;background: #f8f7df">
                        <div style="font:20px Verdana, Geneva, sans-serif;padding-left:10px">Admin Login Here : </div>       
                        <c:if test="${not empty param.message}">

                            <font color="red" size="3" face="Verdana" style="padding-left: 10px">
                            <c:out  value="${param.message}"></c:out>
                            </font>
                            <br/>
                        </c:if>
                    <br/>
                <form onsubmit='return formValidator();' action="loginAdmin.jsp"  name="loginform"  method="post" >
                   
                    <span style="font:18px Verdana, Geneva, sans-serif;padding-left:10px">Username : </span><input type="text" name="uname" id="input"/><br />
                    <span style="font:18px Verdana, Geneva, sans-serif;padding-left:10px">Password : </span> <input type="password" name="pass" id="input2"/>                   
                    <input type="submit" name="submit"  class="submit" value="Login" id="button"/>

                </form>
                </div>


loginAdmin.jsp


<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:import url="include/connection.jsp"></c:import>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    </head>

      <c:if test="${pageContext.request.method=='POST'}" >
          <c:catch var="exc">
              <c:if test="${empty param.uname or empty param.pass }">
                  <c:redirect url="index.jsp" >
                      <c:param name="message" value="Please fill all fields."></c:param>
                  </c:redirect>
              </c:if>
                 
             
        <c:if test="${not empty param.uname and not empty param.pass}">

            <sql:query dataSource="${ds}" var="selectQ">
                select count(*) as kount from tbl_admin where username='${param.uname}' &&  password='${param.pass}'
            </sql:query>
            <c:forEach items="${selectQ.rows}" var="r">
            <c:choose>
                <c:when test="${r.kount gt 0}">
                    <c:set scope="session" var="loginAdmin" value="${param.uname}"/>
                    <c:redirect url="home.jsp"></c:redirect>
                </c:when>

             <c:otherwise>

                <c:redirect url="index.jsp">
                    <c:param name="message" value="Wrong UserName and/or Password" />
                </c:redirect>
                
            </c:otherwise>
            </c:choose>
           
            </c:forEach>
        </c:if>
          </c:catch>
      </c:if>
               <c:if test="${exc!=null}">
                 <c:redirect url="index.jsp">
                     <c:param name="message" value="Wrong UserName and/or Password" />
                 </c:redirect>
               </c:if>           
</html>

AJAX



Index.jsp

<form  name="employee" action="reg_employee.do" method="POST"  >
<span>Country :</span> <select name='country' id='country' onchange="showState(this.value)" style="width: 150px;margin-left: 145px"  > 
                                    <option>Select</option> 
                                    <%
                                        DbConnection dbc = new DbConnection();
                                        Connection con=dbc.getCon();
                                        Statement stmt = con.createStatement(); 
                                        ResultSet rs = stmt.executeQuery("select distinct country from tbl_locations ORDER BY country ASC");
                                        while(rs.next()){
                                            %>
                                            <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option> 
                                            <%
                                        }
                                            %>
                                    </select> 
                                    <br/>  <br />
                            <span>State :</span>
                            <span id='state'> 
                                <select id="state1" name='state' style="width: 150px;margin-left: 165px" >
                                   <option>Select</option>
                                  
                                </select> 
                            </span><br /><br />
                            <span>City :</span>
                                <span id='city'> 
                                    <select id="city1" name='city' style="width: 150px;margin-left: 176px"  > 
                                        <option>Select</option>
                                       
                                    </select> 
                                </span><br /><br />
</form>

Javascript

<script language="javascript" type="text/javascript"> 
      var xmlHttp 
      var xmlHttp
      function showState(str){
      if (typeof XMLHttpRequest != "undefined"){
      xmlHttp= new XMLHttpRequest();
      }
      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 +="?country=" +str;
      xmlHttp.onreadystatechange = stateChange;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
      }

      function stateChange(){  
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){  
      document.getElementById("state").innerHTML=xmlHttp.responseText  
      }  
      }

      function showCity(str){
      if (typeof XMLHttpRequest != "undefined"){
        xmlHttp= new XMLHttpRequest();
        }
      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 +="?state=" +str;
      xmlHttp.onreadystatechange = stateChange1;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
      }
      function stateChange1(){  
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){  
      document.getElementById("city").innerHTML=xmlHttp.responseText  
      }  
      }
      </script>  

State.jsp

<%@page import="model.DbConnection"%>
<%@page import="java.sql.*"%>
<%
String country=request.getParameter("country"); 
String buffer="";
buffer="<select name='state' id='state1' onchange='showCity(this.value);' class='state' ><option>Select</option>"; 
try{

     DbConnection dbc = new DbConnection();
     Connection con=dbc.getCon();
 Statement stmt = con.createStatement(); 
 ResultSet rs = stmt.executeQuery("Select distinct state from tbl_locations where country='"+country+"' ORDER BY state ASC"); 
   while(rs.next()){
   buffer=buffer+"<option value='"+rs.getString(1)+"'>"+rs.getString(1)+"</option>"; 
   } 
 buffer=buffer+"</select>"; 
 response.getWriter().println(buffer);
 }
 catch(Exception e){
     System.out.println(e);
 }

 %>

City.jsp

<%@page import="model.DbConnection"%>
<%@page import="java.sql.*"%>
<%
String state=request.getParameter("state");  
String buffer="";
buffer="<select name='city' id='city1' class='city' ><option>Select</option>"; 
try{
DbConnection dbc = new DbConnection();
Connection con=dbc.getCon();
 Statement stmt = con.createStatement(); 

 ResultSet rs = stmt.executeQuery("Select distinct city from tbl_locations  where state='"+state+"' ORDER BY city ASC"); 
   while(rs.next()){
   buffer=buffer+"<option value='"+rs.getString(1)+"'>"+rs.getString(1)+"</option>"; 
   } 
 buffer=buffer+"</select>"; 
 response.getWriter().println(buffer);
 }
 catch(Exception e){
     System.out.println(e);
 }
 %>