2012-11-27 44 views
0

我希望在提交我的表單之後再出於某種原因再次轉發到同一頁面時,下拉列表中的所選選項應該保留我第一次輸入的選定值。如何將選定的值保留在同一個jsp頁面的下拉列表中?

<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文件上,現在如果我們看到下拉菜單,那麼將會選擇「英格蘭」,但是我想'西班牙',因爲用戶選擇'西班牙'。 – Ramesh

回答

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> 

在你的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); 
} 

現在,當您第二次進入該頁面時,您會看到選定的值。

相關問題