java.util.List 元素作为 HTML select 选项元素在 JSP 页面中 - 使用哪种方式?
java.util.List elements as HTML select option elements in JSP page - which way to use?
我使用 Spring 框架,我将不同类型的值放入 ModelAndView-s,然后尝试在我的 jsp 页面中使用它们。当我使用 String 值时,很简单,我将它放入 ModelAndView:
mv.addObject("stringValue", "Hello Whosebug");
而且我在jsp页面上看到了(据我所知,这种方法叫做JSP EL):
<input type="text" id="stringValue" name="stringValue" value="${stringValue}">
但是当我尝试对列表元素执行相同操作时:
mv.addObject("listElements", Arrays.asList("first", "second", "third", "fourth"));
我发现很难在我的 JSP 页面中使用它们。我可以用 JSP 脚本来处理它们:
<select id="positionT" name="positionT" class="form-control">
<%List<String> elements = (List<String>) request.getAttribute("listElements");
for(String actElement : elements){
%>
<option value="<%=actElement %>"><%=actElement %></option>
<%} %>
</select>
但我读到使用 JSP scriplets 已经过时了。我还找到了 JSTL 和 Spring 标签库的解决方案。我对 Apache Velocity 和 Freemarker 了解一些,所以我知道它们会是一个很好的解决方案。但是有没有解决方案,我不必使用任何类型的库或任何类型的模板引擎?还要避免 JSP scriplets?就像我使用简单字符串值的方式一样。还有人可以告诉我为什么 JSP scriplets 已经过时了吗?很抱歉提出愚蠢的问题,我对不同技术的了解越多,我就越对它们感到困惑。
如果您想将它们列在 select 中,您应该可以这样做:
<form:select path="listElements">
<form:options items="${listElements}"></form:options>
</form:select>
我使用 Spring 框架,我将不同类型的值放入 ModelAndView-s,然后尝试在我的 jsp 页面中使用它们。当我使用 String 值时,很简单,我将它放入 ModelAndView:
mv.addObject("stringValue", "Hello Whosebug");
而且我在jsp页面上看到了(据我所知,这种方法叫做JSP EL):
<input type="text" id="stringValue" name="stringValue" value="${stringValue}">
但是当我尝试对列表元素执行相同操作时:
mv.addObject("listElements", Arrays.asList("first", "second", "third", "fourth"));
我发现很难在我的 JSP 页面中使用它们。我可以用 JSP 脚本来处理它们:
<select id="positionT" name="positionT" class="form-control">
<%List<String> elements = (List<String>) request.getAttribute("listElements");
for(String actElement : elements){
%>
<option value="<%=actElement %>"><%=actElement %></option>
<%} %>
</select>
但我读到使用 JSP scriplets 已经过时了。我还找到了 JSTL 和 Spring 标签库的解决方案。我对 Apache Velocity 和 Freemarker 了解一些,所以我知道它们会是一个很好的解决方案。但是有没有解决方案,我不必使用任何类型的库或任何类型的模板引擎?还要避免 JSP scriplets?就像我使用简单字符串值的方式一样。还有人可以告诉我为什么 JSP scriplets 已经过时了吗?很抱歉提出愚蠢的问题,我对不同技术的了解越多,我就越对它们感到困惑。
如果您想将它们列在 select 中,您应该可以这样做:
<form:select path="listElements">
<form:options items="${listElements}"></form:options>
</form:select>