Why you are putting hard coded city list in your select menu? To do that your jsp page should look like bellow using 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>
In your servlet mapped with your <SUBMITTING_URL>
should have a doPost
method like bellow:
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
}
}
And your doGet method should look like bellow:
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);
}
Now when you like to go to the page second time, you will see the selected value, you have chosen.