Thursday, 3 October 2013

How to fill Dynamic Dropdown list in Spring.

In this tutorial we will learn "how to fill dynamic dropdown list in spring and hibernate using ajax and Json".

Let us impletement this feature in Spring MVC application using Json and ajax.

For this we have to create following Java Class file


let's start example

Domain

1. CountryBean.java file

package com.bean;

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


/**
 *
 * @author rajnikant panchal
 */
@Entity
@Table(name="country")
public class CountryBean {

    @Id
    @Column(name="countryId")
    @GeneratedValue
    private Integer countryId;
    
    @Column(name="countryName")
    private String countryName;
        
    
    public Integer getCountryId() {
        return countryId;
    }

    public void setCountryId(Integer countryId) {
        this.countryId = countryId;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    
}

  • In this we mapped country table and make getter and setter for variables.

2. StateBean.java file



package com.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 *
 * @author rajnikant panchal
 */
@Entity
@Table(name="state")
public class StateBean {
    
    
    @Id
    @Column(name="stateId")
    @GeneratedValue
    private Integer stateId;
    
    @Column(name="stateName")
    private String stateName;
    
    @ManyToOne
    @JoinColumn(name="countryId", insertable = false, updatable = false)
    private CountryBean country;
    
    @Column(name = "countryId")
    private Integer countryId;

    public Integer getCountryId() {
        return countryId;
    }

    public void setCountryId(Integer countryId) {
        this.countryId = countryId;
    }
    
    
    public Integer getStateId() {
        return stateId;
    }

    public void setStateId(Integer stateId) {
        this.stateId = stateId;
    }

    public String getStateName() {
        return stateName;
    }

    public void setStateName(String stateName) {
        this.stateName = stateName;
    }

    public CountryBean getCountry() {
        return country;
    }

    public void setCountry(CountryBean country) {
        this.country = country;
    }
    
        
}

  • In this we mapped state table and make getter and setter for variables and also defined countryId as foreign key.


DaoLayer

In this layer we create database accessing object and interact with database and create two method loadState and loadCountry.

StateDao.java file

package com.dao;

import com.bean.CountryBean;
import com.bean.StateBean;
import java.util.List;

/**
 *
 * @author rajnikant panchal
 */
public interface StateDao {
    
    public List<StateBean> loadState(Integer countryId);
    public List<CountryBean> listCountry123();
    
}


StateDaoImpl.java file

package com.dao;

import com.bean.CountryBean;
import com.bean.StateBean;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author rajnikant panchal
 */
@Repository
public class StateDaoImpl implements StateDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }



@Override

public List<CountryBean> listCountry(){

        return getCurrentSession().createQuery("from CountryBean").list();
    }

@Override
public List<StateBean> loadState(Integer countryId) {

        return getCurrentSession().createQuery("from StateBean s where s.countryId=" + countryId + ")").list();

    }


}



ServiceLayer

In this layer we create one interface and one java file for defining method and accessing this method using dao object

StateService.java file

package com.service;

import com.bean.CountryBean;
import com.bean.StateBean;
import java.util.List;

/**
 *
 * @author root
 */
public interface StateService {
      
    public List<StateBean> loadState(Integer countryId);
    public List<CountryBean> listCountry();
    
}


StateServiceImpl.java file


package com.service;

import com.bean.CountryBean;
import com.bean.StateBean;
import com.dao.StateDao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author rajnikant panchal
 */
@Service
public class StateServiceImpl implements StateService{

    @Autowired
    private StateDao stateDao;
    
    @Override
    @Transactional
    public List<StateBean> loadState(Integer countryId) {
        return stateDao.loadState(countryId);
    }

    @Override
    @Transactional
    public List<CountryBean> listCountry() {
        return stateDao.listCountry();
                
    }
 }



Controller Layer

We now create one Controller for interacting with jsp and dao.

StateController.java file


package com.controller;

import com.bean.StateBean;
import com.service.StateService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author rajnikant panchal
 */

@Controller
public class StateController {

    
    @Autowired
    private StateService stateService;
    private ModelAndView mav;

    @RequestMapping(value = "/loadCountry", method = RequestMethod.GET)
    public ModelAndView loadCountry() {

        mav = new ModelAndView();
        mav.addObject("countryList", stateService.listCountry());
        
        return mav;
    }

    @RequestMapping(value = "/loadStates", headers = "Accept=*/*", method = RequestMethod.GET)
    public @ResponseBody
    List<StateBean> loadStates(@RequestParam(value = "countryId", required = true) Integer countryId) throws IllegalStateException {

        //Specify the returning object you want here
        return stateService.loadState(countryId);
    }
}


ViewLayer 

In this layer we define jsp.

index.jsp


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@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>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    </head>
    <script>
        
        $(document).ready(
        function() {

            $('#countryId').change(
            function() {
                
                $.getJSON('loadStates.htm', {
                    countryId : $(this).val(),
                    ajax : 'true'
                }, function(data) {
                    
                    var html = '<option value="">----Select State----</option>';
                    var len = data.length;
      
                    for ( var i = 0; i < len; i++) {
                        html += '<option value="' + data[i].stateId + '">' + data[i].stateName + '</option>';
                    }
                    html += '</option>';
   
                    $('#stateId').html(html);
                });
            });
            
        });
        
    </script>

    <body>

        <h3>Countries</h3>

        <table class="data">
            
            <tr>
                <td>Country-Name</td>
                <td>
                    <select id="countryId" name="countryId">
                        <option value="">Select Country</option> 
                        <c:forEach items="${countryList}" var="country">
                            <option   value="${country.countryId}"  >${country.countryName}</option>
                        </c:forEach>
                    </select>
                </td>
            </tr>

            <tr>
                <td>State-Name</td>
                <td>
                    <select  id="stateId">
                        <option value="">Select State</option> 
                    </select>
                </td>
            </tr>                    
        </table>
    </body>
</html>



after creating above class files you have to 
set annotation configuration in spring-servlet.xml file.
jdbc.properties file for database connection.
set hibernate configuration file.

also you have to add following extra jars into project

jackson-core-asl-1.9.7.jar
jackson-mapper-asl-1.9.7.jar
mysql-connector-java-5.1.21.jar


Regards
Rajnikant Panchal


3 comments:

  1. Waste of time.. no use, not working

    ReplyDelete
  2. It works! Thank you very much! Solved my problem!

    ReplyDelete
  3. Hi, I'm beginner in this and it would be helpful if u provide the latest code to run in spring boot and how to run it in detail.. Thanks!!

    ReplyDelete