Spring MVC form:selectタグを使うサンプル
環境
Spring 5.2.22
Eclipse 4.24.0
操作方法
1.画面表示用モデルを作成します(SelectModel.java)
public class SelectModel {
private String selectedCity;
private List<String> selectedCitys;
}
2.コントローラは以下のようになります。
@Controller
public class FormController {
@RequestMapping(value = "/select", method = RequestMethod.GET)
public String select(Model model) {
//Cityクラスのオブジェクト型のリストの宣言
List<City> citys = new ArrayList<>();
// オブジェクトの要素をリストに追加する
citys.add(new City("101", "東京"));
citys.add(new City("202", "大阪"));
citys.add(new City("303", "福岡"));
//画面表示用モデルの宣言
SelectModel sme = new SelectModel();
sme.setSelectedCity("202");
//String型のリストの宣言
List<String> selectedCitys = new ArrayList<String>();
selectedCitys.add("101");
selectedCitys.add("303");
sme.setSelectedCitys(selectedCitys);
//属性追加
model.addAttribute("selectModel", sme);
model.addAttribute("citys", city);
return "select";
}
}
3.JSP画面
書式
form:select path="フィールド名" items="${リストまたは配列名}" itemLabel="クラスのプロパティ名" itemValue="city" size="3″ multiple="true"
itemLabel labelを出力するitemsで指定したクラスのプロパティ名
itemValue valueを出力するitemsで指定したクラスのプロパティ名
multiple HTML標準のmultiple属性
size HTML標準のsize属性
サンプルコード
<form:form modelAttribute="selectModel">
<form:select path="selectedCity" items="${citys}" itemLabel="title" itemValue="city" /><br>
<form:select path="selectedCitys" items="${citys}" itemLabel="title" itemValue="city" size="3" multiple="true" />
</form:form>