【问题标题】:Drop down list in struts2struts2中的下拉列表
【发布时间】:2012-03-06 10:20:39
【问题描述】:

如何在 struts2 中从数据库中填充网页中的 ddropdown 列表。下拉列表的项目将从数据库中获取。

【问题讨论】:

  • 请提供更多详细信息...您可以举一个输入和所需输出的示例。到目前为止,您尝试了哪些方法?
  • 我正在创建一个网页,我必须在其中选择国家名称。国家名称不能硬编码,因为它经常更改,因此下拉列表中的项目将从包含国家名称的数据库中填充。
  • 好的。您能否展示一下您目前拥有的代码?

标签: struts2


【解决方案1】:

为了在struts2中创建列表,我们可以使用Preparable实现。

public class CountryListAction extends ActionSupport implements Preparable {

 private List<String> country;
 getters and setters 

 public String prepareCountryList() throws Exception{

  country=new ArrayList<String>();
  country=fill country from database;

 }

 public String countryList() throws Exception{
  return SUCCESS;
 }

} 

对于jsp,使用:

<s:select label="Select Country"
   name="country"
   headerValue="Select Country"
   list="%{country}"
/>

Preparable 接口会在调用 countryList 之前调用 prepareCountryList 方法,并预填充 jsp。您可以使用 struts2 中的单一方法填充尽可能多的下拉列表。

【讨论】:

    【解决方案2】:

    您需要使用 getter 和 setter 在您的操作类中创建一个列表,您所要做的就是在您的操作的执行方法中填充列表。

    动作类

    public class MyListAction extends ActionSupport{
    
      private List<String> country;
      getters and setters 
    
      public String execute() throws Exception{
    
        country=new ArrayList<String>();
        countr=fill country from database;
        return SUCCESS;
      }
    
    }
    

    现在你只需要一个带有以下条目的 S2 选择标签

    <s:select label="Select Country"
           name="country"
           headerKey="-1" headerValue="Select Country"
           list="%{country}"
    
    />
    

    这里 list 是一个可迭代的源来填充。如果列表是 Map (key, value),则 Map 键将成为选项 'value' 参数,而 Map 值将成为选项主体。 因此list=%{country} 将由 OGNL 作为您的操作类中的 getCountry() 方法进行评估,并将从值堆栈中获取所需的列表以填充下拉列表

    【讨论】:

      【解决方案3】:

      您可以使用以下代码:

         <s:select name="someName" id="someId" 
      list="someMap_or_List" onchange="someFunction();"/>
      

      这里 someMap_or_List 是您可以用来填充下拉列表的列表或地图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多