2016年6月6日 星期一

寫一個 HTML 傳送表單資料至 JSP

說明:
寫兩個檔案:

  1. request.html → 做一個表單,可傳送資料出去。
  2. request.jsp → 讀取 get 請求,並輸出傳來的資料內容。

---
前言:
HTTP Request 請求,常用的有 GET 及 POST 方法,於網路查詢即可得知兩者差異,這邊就不加說明,直接 codeing 實作。

##ReadMore##
---
兩檔案路徑同樣放至:/opt/apache-tomcat-8.0.30/webapps/Test/

---
request.html
<html>
  <head>>
 
  </head>
   
  <body>
    <form action="request.jsp" method="get">
               請輸入資訊:<input type="text" name="info">
      <input type="submit" value="傳送">
    </form> 
  </body>
</html>

---
request.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

</head>

<body>
<% 
request.setCharacterEncoding("UTF-8");
//String content=new String(request.getParameter("info").getBytes("UTF-8"));
String content = request.getParameter("info");

if(content == null){
    content = "null";
}else{
    content = new String(request.getParameter("info").getBytes("UTF-8"));       
}
//String content=request.getParameter("info");
%>                                                          
<h2>顯示…</h2>                                              
<h2>收到的訊息:<%=content %></h2>                          
</body>                                                     
</html>

---
測試網址:
http://localhost:8080/Test/request.html

送出表單後,會直接跳轉至
http://localhost:8080/Test/request.jsp

---
也可以硬改網址,直接加入參數及資料給 JSP,例如:
http://localhost:8080/Test/request.jsp?info=hehe

因此也可以發現,從安全性來看,POST (資料參數不會附在網址上)遠優於 GET 求請方式。

沒有留言:

張貼留言