閱讀目錄(content)
•1.get與post的區別
•1.1 get方法 jsp中的代碼form表單代碼
•1.2 action包中servlet的doget方法中的代碼
•2.運行結果
•2.1 輸入數據
•2.2 打印出數據
•3.post方法
•4.對比
•4.1 在輸出頁面按下f12查看
•5.分析
1.get與post的區別
get和post方法都是對服務器的請求方式,只是他們傳輸表單的方式不一樣。
下面我們就以傳輸一個表單的數據為例,來分析get與post的區別
1.1 get方法 jsp中的代碼form表單代碼
1.2 action包中servlet的doget方法中的代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype( "text/html;charset=gbk" ); //設置響應正文的mime類型 request.setcharacterencoding( "gbk" ); //設置請求的編碼格式 response.setcharacterencoding( "gbk" ); string username = request.getparameter( "username" ); // string password = request.getparameter( "password" ); string sex = request.getparameter( "sex" ); string classes = request.getparameter( "class" ); string hobby[] = request.getparametervalues( "hobby" ); // 獲取checkbox的數據保存到hobby數組中 printwriter out = response.getwriter(); if (hobby != null ) { for (string x: hobby) { out.println( "doget被調用" ); out.println( "name:" +username+ "password:" +password+ "sex" +sex+ "classes" +classes); out.println( "hobby:" + x); } } else { out.println( "此人沒愛好!" ); } } |
注意: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文件中
以上這篇java web學習_淺談request對象中get和post的差異就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。