How to get value from DB in Struts 2 dropdown along with list

落花浮王杯 提交于 2019-12-25 02:10:24

问题


I am using Struts2 framework for my application and my code is as follows,

/*Setting dynamic dropdown of service Type*/
ShowSearch drop=new ShowSearch();
service=drop.serviceType();
setService(service);

I am getting list of values from DB (Lets say values are "Apple","Cat","Jack","Zag") and it has shown in struts2 dropdown as mentioned in JSP .

<s:select id="serviceType" name="serviceType"
     label="What is the service offering" required="true"
     value="%{serviceType}" list="service" />

When I am trying to do below action, lets say localhost:8080/as/prd?id=first Actual Value of the "serviceType" dropdown for 'first' is "Jack". But now, dropdown is showing in the order which is taken from DB (i.e based on list "Service").

My requirement is to show "Jack" then following "Apple","Cat","Zag",.... What should I do to show like that?


回答1:


set that string variable in your action class. Then that string variable will be displayed first in the dropdown.




回答2:


Show like that is called sorting in the alphabetical order. To do that you could modify the list before the rendering phase. Assume your list collection element is a simple string, then

Collections.sort(myList);

will do what you want.

Another approach is to use s:sort tag and write a comparator which sort the list, then wrap it around the s:select tag

<s:sort comparator="myComparator" source="myList">
<s:select id="serviceType" name="serviceType"
             label="What is the service offering" required="true"
             value="%{serviceType}" list="myList" />
</s:sort>

Write a simple comparator

public Comparator getMyComparator() {
  return new Comparator() {
    public int compare(Object o1, Object o2) {
      String s1 = (String) o1;
      String s2 = (String) o2;

      return s1.compareTo(s2);
    }
  };
}

More detailed explanation how to sort collections and how to use Comparable and Comparator you could find here.



来源:https://stackoverflow.com/questions/19853108/how-to-get-value-from-db-in-struts-2-dropdown-along-with-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!