1. 程式人生 > >javaweb—HttpServletRequest和HttpServletResponse物件

javaweb—HttpServletRequest和HttpServletResponse物件

**GETPOST提交

主要區別:

# 1Get是用來從伺服器上獲得資料,而Post是用來向伺服器上傳遞資料。例如我們訪問網站都是Get方式,而我們的影象上傳則是Post
# 2Get將表單中資料的按照variable=value的形式,新增到action所指向的URL後面,並且兩者使用“?”連線,各個變數之間使用“&”連線;Post是將表單中的資料放在form的實體內容中,按照變數和值相對應的方式,傳遞到action所指向URL
# 3
Get是不安全的,因為資料被放在請求的URL中。Post的所有操作對使用者來說都是不可見的。
# 4
Get傳輸的資料量小,一般小於1K

;而Post可以傳輸大量的資料。
# 5
Get限制Form表單的資料集的值必須為ASCII字元;而Post支援整個ISO10646字符集。預設是用ISO-8859-1編碼。

** HttpServletRequest物件

HttpServletRequest物件代表客戶端的請求,當客戶端通過HTTP協議訪問伺服器時,HTTP請求頭中的所有資訊都封裝在這個物件中,通過這個物件提供的方法,可以獲得客戶端請求的所有資訊。

protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

/**

 * request物件中取出請求資料

 * */

// 獲取請求方方式

System.out.println("請求方式:"+request.getMethod());

// 獲取資源的URI

System.out.println("URI"+request.getRequestURI());

// 獲取資源的URL

System.out.println("URL:"+request.getRequestURL());

// 獲取http版本

System.out.println("http版本號:"+request.getProtocol());

    //-------------------------------------------------------

// 獲取host請求頭名稱

System.out.println("頭名稱:"+request.getHeader("Host"));

// 獲取所有的請求頭

System.out.println("所有的請求頭名稱列表");

Enumeration<String> elem = request.getHeaderNames();

while (elem.hasMoreElements()) {

String headerName = (String) elem.nextElement();

String headerValue=(String) request.getHeader(headerName);

System.out.println(headerName+": "+headerValue);

}

//-------------------------------------------------------  

}

// 採用的是post方法

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

InputStream is=request.getInputStream();// 得到實體輸入流

byte[] buf=new byte[1024];

int len=0;

while ((len=is.read(buf))!=-1) {

System.out.println(new String(buf,0,len));

}

    }

結果:

請求servletGet方法

請求方式:GET

URI/ibatis01/FuncDemo

URL:http://localhost:8080/ibatis01/FuncDemo

http版本號:HTTP/1.1

頭名稱:localhost:8080

所有的請求頭名稱列表

accept: text/html, application/xhtml+xml, image/jxr, */*

accept-language: zh-Hans-CN,zh-Hans;q=0.5

user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586

accept-encoding: gzip, deflate

host: localhost:8080

connection: Keep-Alive

cookie: bdshare_firstime=1464055541439

請求servletPost方法,獲取Post物件的實體內容

name=wxh&pwd=123

** 獲取引數物件方式

#1. 通過getParameter(“XXX”)方法獲取

#2. 通過Enumeration<T>遍歷requestname集合,用name取出對應的value

#3. 還有一個getParameterValues(“XXX”)獲取一個那麼有多個value物件,它返回的是一個String[]型別的資料,在遍歷這個資料集合就可以取出所有的資料

** 引數內容編碼問題

不論是post還是get都會出現亂碼問題,因為jsp端設定的是utf-8的編碼格式,而servlet解析用的預設的是iso-8853-1的編碼格式。[中文亂碼]

一般有兩種解決方案

#1. 手動解碼方式[iso-8853-1 à utf-8]

name=new String(name.getBytes("iso-8859-1"),"utf-8");

#2. setCharacterEncoding(“utf-8”)

request.setCharacterEncoding("UTF-8");

注意:setCharacterEncoding(“utf-8”)只有在doPost中才有效,因為post請求中引數的傳遞在實體內容中,而不是url地址後面。

package com.ibatis01.servlet;

import java.io.IOException;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class Request extends HttpServlet {

         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   /**

                    * 設定編碼格式

                    * 但是對get方式沒用

                    * 這個方法只對post提交的實體內容有效

                    * get只能用手動解碼[iso-8853-1 --> utf-8]

                   */

                   request.setCharacterEncoding("UTF-8");// 沒用

                   Enumeration<String> en=request.getParameterNames();// 獲取name集合

                   while (en.hasMoreElements()) {

                            String name = (String) en.nextElement();// 獲取name

                            name=new String(name.getBytes("iso-8859-1"),"utf-8");// 防止亂碼

                            if(name.equals("hobby")){

                                     // 通過getParameterValues(String)獲取多值

                                     String[] values=request.getParameterValues(name);// 獲取value

                                     for (int i = 0; i < values.length; i++) {

                                               values[i]=new String(values[i].getBytes("iso-8859-1"),"utf-8");// 防止亂碼

                                               System.out.println(name+": "+values[i]);

                                     }

                            }else{

                                     String value=request.getParameter(name);

                                      value=new String(value.getBytes("iso-8859-1"),"utf-8");// 防止亂碼

                                     System.out.println(name+": "+value);

                            }

                   }

         }

         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   request.setCharacterEncoding("UTF-8");

                   System.out.println("---- POST方式 ----");

                   /**

                    * 獲取請求的引數

                    * 利用getParameter獲取引數

                    * */

                   String name=request.getParameter("name");

                   String pwd=request.getParameter("pwd");

                   System.out.println("名字:"+name+" | 密碼:"+pwd);

                   /**

                    * 利用Enumeration<T>遍歷獲取全部引數

                    * */

                   Enumeration<String> en=request.getParameterNames();// 獲取Key

                   while (en.hasMoreElements()) {

                            String _name = (String) en.nextElement();

                            String _pwd=(String)request.getParameter(_name);

                            System.out.println(_name+": "+_pwd);

                   }

         }

}

** HttpServletResponse物件

HttpServletResponse物件代表伺服器的響應。這個物件中封裝了向客戶端傳送資料、傳送響應頭,傳送響應狀態碼的方法。

返回的內容分成三大部分:1.狀態碼、2.響應頭、3.實體內容[資料]

常用的幾個方法:

voidaddCookie(Cookie cookie)    將一個Set-Cookie頭標加入到響應。

voidaddDateHeader(String name,long date)    使用指定日期值加入帶有指定名字(或代換所有此名字頭標)的響應頭標的方法。

voidsetHeader(String name,String value)    設定具有指定名字和取值的一個響應頭標。

voidaddIntHeader(String name,int value)    使用指定整型值加入帶有指定名字的響應頭標(或代換此名字的所有頭標)。

boolean containsHeader(Stringname)    如果響應已包含此名字的頭標,則返回true

StringencodeRedirectURL(String url)    如果客戶端不知道接受cookid,則向URL加入會話ID。第一種形式只對在sendRedirect()中使用的URL進行呼叫。其他被編碼的URLs應被傳遞到encodeURL()      

StringencodeURL(String url)          

voidsendError(int status)    設定響應狀態碼為指定值(可選的狀態資訊)。HttpServleetResponse定義了一個完整的整數常量集合表示有效狀態值。

voidsendError(int status,String msg)          

voidsetStatus(int status)    設定響應狀態碼為指定指。只應用於不產生錯誤的響應,而錯誤響應使用sendError()

常見http錯誤:http://blog.sina.com.cn/s/blog_68158ebf0100wr7z.html

package com.ibatis01.servlet;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ResponseDemo extends HttpServlet {

         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   /**

                    * HttpServletResponse物件返回資訊

                   */

                   /**

                    * 1.狀態碼

                   */

                   // 返回狀態

                   //response.setStatus(404);

                   // 返回狀態加錯誤頁面

                   //response.sendError(404);

                   /**

                    * 2.響應頭

                   */

                   response.setHeader("server", "JBoss");

                   /**

                    * 3.實體內容

                   */

                   response.getWriter().write("hello world");// 字元傳送

                   // response.getOutputStream().write("hello world".getBytes());// 位元組傳送

                   // 頁面重定向

                   response.sendRedirect("/ibatis01/login.jsp");

                   // 伺服器傳送給瀏覽器的資料型別和內容編碼

                   response.setContentType("text/html;charset=utf-8");

         }

         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         }

}