为什么要将硬编码的城市列表放在选择菜单中?为此,您的 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);
}
现在,当您想第二次进入该页面时,您将看到已选择的值,您已选择。