java_web學習(六) request對象中的get和post差異,java_webrequest

來源:互聯網
上載者:User

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檔案中

 

 

 

本人還是初學者,高手大神請指教,

 

 

 

 

 

 

    

 

 

 

 

    

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.