Thursday, 19 March 2015

Spring < form:select /> tag selected option Example

In Spring controller , write below code to bind the <form:select />, <form:option /> or <form:options />, we will use bellow value to render HTML form:select box :

@Controller

@RequestMapping("/")

public TestController{

protected ModelAndView createSelectWithValue(HttpServletRequest request) throws Exception { 
 
        Map cData = new HashMap(); 
 
        Map<String,String> countryList = new LinkedHashMap<String,String>(); 
 
        countryList.put("TX", "Texas");
 countryList.put("IN", "India");
 countryList.put("NY", "New York");
 countryList.put("NJ", "New Jessy");
 cData.put("cList", countryList); 
  
        ModelAndView mav=new ModelAndView();
        mav.addAttribute("selectedCountry","IN"); 
        mav.addAttribute("cList",cData);
        mav.setView("index");
  
        return mav;
  }
}
 
 
index.jsp
 
1) Simply display <form:select />

   <form:select path="c" items="${cList}" />
 
   OR
 
   <form:select path="c">
    <form:options items="${cList}" />
   </form:select> 
 
   OR
 
   <form:select path="c">
   <form:option value="NONE" label="--- Select ---"/>
   <form:options items="${cList}" />
   </form:select> 
    

2) Load with selected value specified
 
   <select id="country" name="country">
    <option value=""></option>
 
      <c:forEach items="${cList}" var="name">
        <c:when test="${name[0]== selectedCountry}">
            <option value="${name[0]}" selected>${name[1]}</option>
        </c:when>
        <c:otherwise>
            <option value="${name[0]}" >${name[1]}</option>
        </c:otherwise>
     </c:forEach>
  </select>