Total Pageviews

2011/06/02

利用enumeration type來做下拉選單

我們在開發的時候,會遇到某些下拉選單不是從資料庫抓出來的,寫死在jsp好像不太恰當,寫在property file再抓出來又有點麻煩,如下圖所示,輸出格式、法務科別、下授類別等,下拉單內容很固定、又不需要放在資料庫:


這邊我建議用Java的enumeration type來建立下拉選單。步驟如下(以法務科別為例):

1. 建立enumeration class (若下選選單有增減,只要修改enumeration即可)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
   package gov.fdc.nig.enumeration;
   
   /**
    * 法務科別 enumeration
    *
    * @author albert
    *
    */
   public enum LegalSectionEnum {
   
       SECTION1("1.法務一科", "1"), SECTION2("2.法務二科", "2"), ALL("3.全部", "3");
   
       private final String label;
       private final String value;
   
       public String getLabel() {
           return label;
       }
   
       public String getValue() {
           return value;
       }
   
       private LegalSectionEnum(String label, String value) {
           this.label = label;
           this.value = value;
       }
   
       public static void main(String args[]) {
           LegalSectionEnum[] enumArr = LegalSectionEnum.values();
           for (LegalSectionEnum enumeration: enumArr) {
               System.out.println("label=" + enumeration.getLabel() + ", value=" +
                   enumeration.getValue());
           }
       }
   }

2. 在NIGUtilsConroller增加一個method來抓取enumeration中所定義的values
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
   /**
    * 取得法務科別下拉單
    * 
    * @param res loadDelegationUnitList
    * @param session HttpSession
    * @throws IOException if exception happens
    */
   @RequestMapping(value = "/loadLegalSectionList", method = RequestMethod.POST)
   public @ResponseBody
   void loadLegalSectionList(final HttpServletResponse res, final HttpSession session)
   throws IOException {
       final JSONArray jsonArray = new JSONArray();
   
       try {
           final LegalSectionEnum[] enumArr = LegalSectionEnum.values();
   
           for (LegalSectionEnum enumeration: enumArr) {
               Map map = new HashMap();
               map.put("value", enumeration.getValue());
               map.put("name", enumeration.getLabel());
   
               jsonArray.add(map);
           }
       } catch (FDCDataAccessException e) {
           LoggerFactory.getLogger(this.getClass()).debug(
               "loadExportFormatList exception: " + e.getMessage());
       }
   
       res.setContentType(NigAccessKey.JKEY_CONTENT_TYPE);
       res.getWriter().write(jsonArray.toString());
   }


3. 在nig.utils.js增加一個function來取得法務科別下拉單


4. 在功能相對應的js,呼叫nig.utils.js所定義的JavaScript function


JavaScript function所定義的id,與下拉選單的id需要對應

No comments: