JSP Servlet之 form表单 与Servlet之间的参数传送

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 {

	@Override
	protected 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");
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(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

 

结果:

 

 

 

展开阅读全文

没有更多推荐了,返回首页