一、瀏覽器傳遞信息的兩種方法
1.get方法
GET 方法向頁面請求發送已編碼的用戶信息。頁面和已編碼的信息中間用 ? 字符分隔,如下所示:
http://www.test.com/hello?key1=value1&key2=value2
GET 方法是默認的從瀏覽器向 Web 服務器傳遞信息的方法,它會產生一個很長的字符串,出現在瀏覽器的地址欄中。如果您要向服務器傳遞的是密碼或其他的敏感信息,請不要使用 GET 方法。GET 方法有大小限制:請求字符串中最多只能有 1024 個字符。
這些信息使用 QUERY_STRING 頭傳遞,並可以通過 QUERY_STRING 環境變量訪問,Servlet 使用 doGet() 方法處理這種類型的請求。
2.post方法
另一個向後臺程序傳遞信息的比較可靠的方法是 POST 方法。POST 方法打包信息的方式與 GET 方法基本相同,但是 POST 方法不是把信息作爲 URL 中 ? 字符後的文本字符串進行發送,而是把這些信息作爲一個單獨的消息。消息以標準輸出的形式傳到後臺程序,您可以解析和使用這些標準輸出。Servlet 使用 doPost() 方法處理這種類型的請求。
二、使用get傳遞信息的實例
package duan;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "使用 GET 方法處理數據";
response.getWriter().write("hello,world");
String docType = "<!DOCTYPE html> \n";
String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>姓名</b>:"
+ name + "\n" +
" <li><b>say</b>:"
+ request.getParameter("say") + "\n" +
"</ul>\n" +
"</body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
注意這段獲取參數值的代碼
request.getParameter("say")
然後在瀏覽器上輸入
http://localhost:8080/myweb/HelloServlet?name=duan&say=hello!得到如下顯示
三、使用表單get方法實例
上面的HelloServlet代碼不變,增加名字爲hello的html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>my_hello_test</title>
</head>
<body>
<form action="HelloServlet" method="GET">
姓名<input type="text" name="name">
<br />
要說的話:<input type="text" name="say" />
<input type="submit" value="提交" />
</form>
</body>
</html>
然後打開網址localhost:8080/myweb/hello.html
點擊提交
注意form標籤的那一段代碼
<form action="HelloServlet" method="GET">
姓名<input type="text" name="name">
<br />
要說的話:<input type="text" name="say" />
<input type="submit" value="提交" />
</form>