根据java spring注释中dropdown1的选择填充dropdown2

时间:2017-11-05 11:47:31

标签: java spring jsp spring-mvc spring-annotations

Java代码包含以下内容:

@ModelAttribute("countries")
public List<Country> initializeCountries() {

    List <Country> countries = countryService.findAllCountrys();

    return countries;
}  

我使用以下代码成功填充了国家/地区:

<form:select path="country" id="country">
    <form:option value="">Select Country</form:option>
    <form:options items="${countries}" itemValue="countryCode" itemLabel 
     = "countryName" />
</form:select>
<form:errors path="country" cssClass="error"/> 

我有以下代码,它根据countryCode获取状态:

List <State> states = countryService.findAllStatesOfCountry(countryCode);

我应该如何编写java代码和jsp代码,以根据国家/地区的选择填充状态下拉列表。没有在spring注释中使用Ajax / javascript还有其他方法吗?试图找到这个选项。

如果不是因为我尝试使用Ajax最好的水平,请提及详细信息。我是Ajax的新手,因此请分享要加载到jsp文件中的maven依赖项,js和css文件。

1 个答案:

答案 0 :(得分:0)

可以在不使用ajax的情况下实现(尽管这里首选使用ajax / javascript)。

 <script language="javascript">
     function getStates(selectedCountry)
     {
    window.location.href='/getStates?country='+selectedCountry; 
     }

     </script>

<form:select path="country" id="country">
    <form:option value="">Select Country</form:option>
    <form:options items="${countries}" itemValue="countryCode" itemLabel 
     = "countryName" onchange="javascript:getStates(this.value)"/>
</form:select>

    <form:select path="state" id="state">
        <form:option value="">Select State</form:option>
<c:if test="${not empty states}" >
        <form:options items="${states}" itemValue="stateCode" itemLabel 
         = "stateName"/>
</c:if>
    </form:select>
  • onchange属性被添加到javascript函数调用中。它会    获取所选的国家/地区值并将其传递给控制器    请求参数为country。因此,在更改国家/地区时,将进行服务器调用以获取给定国家/地区的状态,并且将刷新页面。
  • 状态的新下拉列表添加了c:if,以便仅在存在属性states时填充状态下拉列表    在请求中。

在控制器端,您将编写如下内容

    @RequestMapping("/getStates")
        public ModelAndView getStates(@RequestParam("country")String countryCode){
       ModelAndView mv = new ModelAndView("yourCurrentView");     
List<States> states = stateService.findAllStatesOfCountry(countryCode);
    mv.add("states",states);
    //to make sure countries drop down also has data
    mv.add("countries",countries);
    }
相关问题