JSP Servlet之 form表單 與Servlet之間的參數傳送
//index.html<html> <head> <title>welcome</title> </head> <body> <form name="myForm" method="post"action="myServlet/PassParams"> <table border="1"> <tr> <td>param1 </td> <td><input name="param1"type="text" /></td> </tr> <tr> <td>param2 </td> <td><input name="param2"type="text" /></td> </tr> <tr> <td>param3 </td> <td><input name="param3"type="text"/></td> </tr> <tr> <td> </td> <td><input type="submit"value="mySubmit"/></td> </tr> </table> </form> </body></html>
然後PassParams這個Servlet的doget / dopost 來處理參數param1—3
package myServlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.PrintWriter;public class PassParams extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {PrintWriter out = resp.getWriter();out.write("doGet\r\n");out.write(req.getParameter("param1"));out.write("\r\n");out.write(req.getParameter("param2"));out.write("\r\n");out.write(req.getParameter("param3"));out.write("\r\n");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubdoGet(req,resp);}/** * */private static final long serialVersionUID = 1L;}
/////////////////////////////
就是html用post方式提交表單,然後PassParams接收參數,並處理..
<form name="myForm"method="post" action="myServlet/PassParams">
action這個參數表示
action |
URL |
規定當提交表單時,向何處發送表單資料。 |
method |
· get · post |
規定如何發送表單資料。 |
用post會比較多,不會在url上顯示出表單的資料,而get就會….
<input name="param1" type="text"/>表示
name |
field_name |
定義 input 元素的名稱。 |
Servlet中,req.getParameter("param1")這樣就在Servlet中取得了參數param1的值…
Web.xml裡要加入:
<servlet> <servlet-name>PassParams</servlet-name> <servlet-class>myServlet.PassParams</servlet-class> </servlet> <servlet-mapping> <servlet-name>PassParams</servlet-name> <url-pattern>/myServlet/PassParams</url-pattern> </servlet-mapping>
/////////////////////////////////////////////////////////////////////////////
其中<url-pattern>/myServlet/PassParams</url-pattern>
表示訪問這個Servlet的路徑….最終就是:
PassParams的dopost訪問路徑:
http://localhost:8080/PassParams/myServlet/PassParams
例:
http://localhost:8080/PassParams/index.html
結果: