我希望在提交表单后再由于某种原因再次转发到同一页面时,下拉列表中的所选选项应保留我第一次输入的选定值。
<form action="CitySelection" method="POST">
<select name="cityname" id="myselect" onchange="this.form.submit()">
<option value="england">england</option>
<option value="france">france</option>
<option value="spain">spain</option>
</select>
</form>
如何通过此功能增强我的上述表单代码,任何建议?
答案 0 :(得分:0)
为什么要在选择菜单中放置硬编码城市列表?要做到这一点,您的jsp页面应该使用c taglib
:
<%@ taglib prefix="c" uri="java.sun.com/jsp/jstl/core" %>
<form action="<SUBMITTING_URL>" method="post">
<select name="cityname" id="myselect" onchange="this.form.submit()">
<c:foreach var="cityname" items="${cityList}">
<c:choose>
<c:when test="${not empty selectedCity && selectedCity eq cityname}">
<option value="${cityname}" selected = "true">${cityname}</option>
</c:when>
<c:otherwise>
<option value="${cityname}">${cityname}</option>
</c:otherwise>
</c:choose>
</c:foreach>
</select>
</form>
在与<SUBMITTING_URL>
映射的servlet中应该有一个doPost
方法,如下所示:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cityName = request.getParameter("cityname"); //retrieving value from post request.
//do your necessary coding.
if(validation error or as your wish){
List<String> cityList = new ArrayList<String>();
cityList.add("england");
cityList.add("france");
cityList.add("spain");
request.setAttribute("cityList",cityList);
request.setAttribute("selectedCity",cityName);
RequestDispatcher dispatcher = request.getRequestDispatcher("cityform.jsp");
dispatcher.forward(request, response);
} else {
//do other things
}
}
你的doGet方法看起来应该如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> cityList = new ArrayList<String>();
cityList.add("england");
cityList.add("france");
cityList.add("spain");
request.setAttribute("cityList",cityList);
request.setAttribute("selectedCity",null);
RequestDispatcher dispatcher = request.getRequestDispatcher("cityform.jsp");
dispatcher.forward(request, response);
}
现在,当您想第二次访问该页面时,您将看到所选的值。