爲什麼你在你的選擇菜單中加入硬編碼城市列表?要做到這一點你的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>
在你的servlet與<SUBMITTING_URL>
映射應該有一個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);
}
現在,當您第二次進入該頁面時,您會看到選定的值。
你是什麼意思的「保留」一詞?你能否清楚地解釋你想要做什麼以及你面臨的問題是什麼? –
例如,如果用戶在下拉列表中選擇「西班牙」,然後表單將被提交,那麼將執行操作,然後一些結果將顯示在jsp文件上,現在如果我們看到下拉菜單,那麼將會選擇「英格蘭」,但是我想'西班牙',因爲用戶選擇'西班牙'。 – Ramesh