選択メニューにハードコードされた都市リストを入れているのはなぜですか? これを行うには、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>
必要です。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);
}
2 度目にページに移動すると、選択した値が表示されます。