如index.jsp中代碼所示:
<form action="photoServlet?info=queryPhotoList" method="post" name="form1">
<table width="525" border="0">
<tr>
<pre><span class="STYLE6"><b>城市:</b><select name="city" id="city"> <option value="重慶">重慶</option> <option value="成都">成都</option> <option value="北京">北京</option> <option value="上海">上海</option> </select> <b>地區:</b> <select
name="regin" size="1"> <option value="重慶大學">d</option>重慶大學<option value="西南大學">西南大學</option> <option value="沙坪壩">沙坪壩</option> <option value="北陪">北碚</option> </select> <b>片區: </b><select name="area" size="1"> <option value="六公寓">六公寓 </option>
<option value="明主湖">民主湖</option> <option value="一食堂">一食堂</option> </select> </span></pre>
</tr>
<tr>
<p><span class="STYLE6"><b>新舊:</b>
<select name="time">
<option>最近一週</option>
<option>近一個月</option>
<option>近半年</option>
</select>
</p>
</tr>
</table>
<input type="submit" name="submit" value="進入">
</form>
想要在servlet中獲得下拉列表框中的內容,可以將select包含在form表單中,然後通過<input type="submit" name="submit" value="進入"> 提交到表單中action中servlet的路徑位置,就可以在servlet中通過:String city=request.getParameter("city") 引號中的city就是select下拉列表框中name的值。
如在photoServlet.java中:
public void user_queryPhotoList(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
data = new OperationData();
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String city=request.getParameter("city");
String regin=request.getParameter("regin");
String area=request.getParameter("area");
String time=request.getParameter("time");
city = new String(city.getBytes("iso-8859-1"),"utf-8");
System.out.println("city="+city);
System.out.println("time="+time);
String condition = "city= '" + city + "' and regin='"+regin+"' and area='"+area+"'";
System.out.println("condition="+condition);
condition=null;
List list = data.photo_queryList(condition); // 執行查詢操作
if (list.size() == 0) {
request.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
out.print("<script language=javascript>history.go(-1);</script>");
} else {
request.setAttribute("list", list); // 將查詢的結果保存在request範圍內
request.getRequestDispatcher("infoShow.jsp").forward(
request, response);
}
}
主要的問題是如果代碼中不加:response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
city = new String(city.getBytes("iso-8859-1"),"utf-8");
以及在index.jsp中不加入:
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
取得的city值就是亂碼,這個花了我一天工夫,一開始想到加入 request.setCharacterEncoding("utf-8");就行了,結果不行,又加了response.setContentType("text/html;charset=utf-8"); 還是不行,把index.jsp頁面中charset=gb2312,改成utf-8之後還是不行,又改了回去。
網上找了半天,加入
city = new String(city.getBytes("iso-8859-1"),"utf-8");以爲可以了 ,還是不行。
。到了晚上還沒弄出這個亂碼,網上找了很多也沒找到,實在弄不下去了,看了少年派這個電影之後,又來看了一下,把index.jsp頁面中charset=gb2312,改成utf-8之後出來了。
看來是這個電影把我看出靈感出來了。哈哈哈。寫在這裏給大家有類似問題的童鞋參考下。哈哈。