Spring form:option
Is there any way to mark an option as selected by default, much开发者_JAVA百科 like the selected
attribute in the HTML option
tag like <option value="value1" selected>
?
If the path value of the tag matches the value of options value it will automatically be selected. You don't need anything special
Is there any way to mark an option as selected by default ???
Just use <spring:option Taglib The first one will be automatically selected
<spring:select name="someProperty">
<spring:option value="">Select one</spring:option>
<spring:option value="someValue">Some value<spring:select>
<!--And so on...-->
<spring:select>
or
<spring:select name="someCollection">
<spring:option value="">Select one</spring:option>
<!--Here goes some List added to request-->
<spring:options itemLabel="propertyNameUsedAsLabel" itemValue="propertyNameUsedAsValue"/>
<!--And so on...-->
<spring:select>
I am assuming you are also using Spring MVC. If you have business logic that requires a certain option to be selected by default, move that business logic to the controller - not the JSP.
@RequestMapping(method = RequestMethod.GET)
public ModelAndView helloWorld(){
ModelAndView model = new ModelAndView("HelloWorldPage");
// first we need to give the countries list to the model
model.addObject("countries", countryService.getAllCountries());
// creating the form
ExampleForm form = new ExampleForm();
// setting the default to Germany (de)
form.setCountryCode = "de";
// adding the form (with the default country set) to the model
model.addObject("form", form);
return model;
}
In the JSP, we pass in the countries to the options and spring will automatically have germany selected:
<form:form method="post" commandName="form">
<%-- other fields ... --%>
<form:select path="countryCode">
<form:options items="${countries}" itemValue="countryCode" itemLabel="countryName"/>
</form:select>
<%-- other fields ... --%>
</form:form>
精彩评论