spring mvc中下拉框的复习

时间:2022-12-05 08:58:14


spring mvc中下拉框,其实是很简单的了,但简单的东西还是应该多复习,这次来复习下.


1)controller:

@RequestMapping(value="/phone-page")
private ModelAndView selectTag() {
ModelAndView mav = new ModelAndView("phone-form");

Map<String, String> phones = new HashMap<String, String>();
phones.put("samsung", "SAMSUNG");
phones.put("nokia", "NOKIA");
phones.put("iphone", "IPHONE");

mav.addObject("phonesMap", phones);
mav.addObject("smartphone", new Smartphone());

return mav;
}



这里其实用HashMap去装载下拉列表,然后放到modelandview中去,然后前端的页面jsp



Select phone:
<form:form method="POST" commandName="smartphone" action="phone-result.html">
<table>
<tr>
<td>
[list]
<form:select path="phone" items="${phonesMap}"/>
[/list]
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>



这里的submit演示了选择某个选项后,提交到phone-result这个方法控制器中,


控制器中的方法代码为:



@RequestMapping(value="/phone-result")
private ModelAndView processPhone(@ModelAttribute Smartphone smartphone) {
ModelAndView mav = new ModelAndView("phone-result");
mav.addObject("smartphone", smartphone);
return mav;
}


可以看到<form:form method="POST" commandName="smartphone" action="phone-result.html">,而接受的参数中,用@ModelAttribute Smartphone smartphone接收住了.




2) 第2种方法是在JSP页面中硬编码下拉选项,如:


<form:form method="POST" commandname="smartphone" action="phone-result.html">
<table>
<tbody><tr>
<td>
[list]
<form:select path="phone">
<form:option value="samsung">SAMSUNG</form:option>
<form:option value="nokia">NOKIA</form:option>
<form:option selected="selected" value="htc">HTC</form:option>
<form:option value="iphone">IPHONE</form:option>
</form:select>
[/list]
</td>
</tr>
<tr>
<td>
<input value="Submit" type="submit">
</td>
</tr>
</tbody></table>
</form:form>



当然呈现这个jsp的控制层为:


@RequestMapping(value="/phone-option-page")
private ModelAndView optionTag() {
return new ModelAndView("phone-option-form", "smartphone", new Smartphone());
}




3 最后一个看<form:options>的用法



控制器方法:


@RequestMapping(value="/phone-options-page")
private ModelAndView optionsTag() {
ModelAndView mav = new ModelAndView("phone-options-form");

Map< String, String > phones = new HashMap();
phones.put("samsung", "SAMSUNG");
phones.put("nokia", "NOKIA");
phones.put("iphone", "IPHONE");
phones.put("bberry", "BLACKBERRY");
phones.put("htc", "HTC");

mav.addObject("phonesMap", phones);
mav.addObject("smartphone", new Smartphone());

return mav;
}



注意页面JSP为:


Select phone:
<form:form method="POST" commandname="smartphone" action="phone-result.html">
<table>
<tbody><tr>
<td>
[list]
<form:select path="phone">
<form:option value="-" label="--Select phone">
<form:options items="${phonesMap}">
</form:options></form:option></form:select>
[/list]
</td>
</tr>
<tr>
<td>
<input value="Submit" type="submit">
</td>
</tr>
</tbody></table>
</form:form>