java_web學習(六) request對象中的get和post差異,java_webrequest
1.get與post的區別
Get和Post方法都是對伺服器的請求方式,只是他們傳輸表單的方式不一樣。
下面我們就以傳輸一個表單的資料為例,來分析get與Post的區別
1.1 get方法 jsp中的代碼form表單代碼
1.2 action包中servlet的doGet方法中的代碼
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 response.setContentType("text/html;charset=gbk");//設定響應本文的mime類型 4 request.setCharacterEncoding("gbk");//佈建要求的編碼格式 5 response.setCharacterEncoding("gbk"); 6 7 String username = request.getParameter("userName");// 8 String password = request.getParameter("password"); 9 String sex = request.getParameter("sex");10 String classes = request.getParameter("class");11 String hobby[] = request.getParameterValues("hobby");// 擷取checkbox的資料儲存到hobby數組中12 13 PrintWriter out = response.getWriter();14 15 if (hobby != null) {16 for (String x: hobby) {17 out.println("doGet被調用");18 out.println("name:"+username+"password:"+password+"sex"+sex+"classes"+classes);19 out.println("hobby:" + x); 20 }21 }else{22 out.println("此人沒愛好!"); 23 }24 }
注意:action包中servlet命名與form表單action的名字相同:
2.運行結果 2.1 輸入資料
2.2 列印出資料
3.post方法
只需要將table表單中method改為post:
servlet中有這樣的一行代碼:
同樣能列印出:只是出現了亂碼
4.對比 4.1 在輸出頁面按下F12查看
post跟get的差異,優先選post
post的缺點:
更新web版本可以避免錯誤
servlet程式碼分析
5.分析
servlet作為控制器是不應該輸出內容的,我們應該把要列印的內容放到jsp檔案中
本人還是初學者,高手大神請指教,