• Servlet 学习小结之doPost()方法和doGet()方法


    网上关于这个讨论一大片,我也阅读了很多但是不能够写出来。得到基友指点才能写出这个小结。

    环境:win7 32bit + IDEA社区版 + Tomcat 7.037 + IE 10

    一、当用doPost()处理用户提交的数据的时候:

    servlet代码

       1:  import javax.servlet.ServletException;
       2:  import javax.servlet.http.HttpServlet;
       3:  import javax.servlet.http.HttpServletRequest;
       4:  import javax.servlet.http.HttpServletResponse;
       5:  import java.io.IOException;
       6:  import java.io.PrintWriter;
       7:   
       8:  public class ServletWork01 extends HttpServlet {
       9:   
      10:      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      11:          String username = new String((req.getParameter("username")).getBytes("iso-8859-1"),"gb2312");
      12:   
      13:          String password = req.getParameter("password");
      14:   
      15:   
      16:          resp.setContentType("text/html;charset=gb2312");
      17:          PrintWriter out = resp.getWriter();
      18:   
      19:          if(username!=null && password!=null){
      20:              if(username.equals("admin") ){
      21:                      if( password.equals("123456"))
      22:                          out.println("Welcome admin come back."+"<br>");
      23:                      else
      24:                          out.println("Wrong admin password"+"<br>");
      25:   
      26:              }
      27:              else if(username.equals("张三") ){
      28:                  if( password.equals("1234"))
      29:                      out.println("Welcome 张三 come back."+"<br>");
      30:                  else
      31:                      out.println("Wrong 张三 password"+"<br>");
      32:              }
      33:   
      34:              else {
      35:                  out.println("Welcome "+username+" come back."+"<br>");
      36:              }
      37:      }

    再贴出web.xml

       1:  <?xml version="1.0" encoding="ISO-8859-1"?>
       2:   
       3:   
       4:  <web-app>
       5:   
       6:    <servlet>
       7:        <servlet-name>loginServlet</servlet-name>
       8:        <servlet-class>ServletWork01</servlet-class>
       9:    </servlet>
      10:    
      11:    
      12:    <servlet-mapping>
      13:        <servlet-name>loginServlet</servlet-name>
      14:        <url-pattern>/</url-pattern>
      15:    </servlet-mapping>
      16:    
      17:  </web-app>

    代码很好写,如何去测试呢?

    IE 10 地址栏输入http://localhost:8080/web1/?username=XXXX&password=XXX

    此处的参数是通过URL传递给服务器应用的。当然也可以通过Form并设置method=get来传递参数。

    这样就可以了,浏览器可以相应返回信息。

    二、用doPost()处理数据的时候:

    先看看文档

    doPost
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOExceptionCalled by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is useful when posting information such as credit card numbers. When overriding this method, read the request data, write the response headers, get the response's writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.  The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body.  Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.  When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.  This method does not need to be either safe or idempotent. Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online.  If the HTTP POST request is incorrectly formatted, doPost returns an HTTP "Bad Request" message.   Parameters:req - an HttpServletRequest object that contains the request the client has made of the servletresp - an HttpServletResponse object that contains the response the servlet sends to the client

    数据只能通过是通过form表单并且指定method=post传递给服务器的。

    index.html

       1:  <html>
       2:      <head>
       3:          <title>welcome</title>
       4:      </head>
       5:      <body>
       6:      <form name="myForm" method="post" action="loginServlet">
       7:          <table border="1">
       8:          <tr>
       9:             <td>username </td>
      10:             <td><input name="username"type="text" /></td>       
      11:          </tr>
      12:          <tr>
      13:             <td>password  </td>
      14:             <td><input name="password"type="text" /></td>
      15:          </tr>
      16:          <td>?</td>
      17:              <td><input type="submit"value="mySubmit"/></td>
      18:          </tr>
      19:          </table>
      20:      </form>
      21:      </body>
      22:  </html>

    servlet代码:

       1:      @Override
       2:      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       3:          String username = new String((req.getParameter("username")).getBytes("iso-8859-1"),"gb2312");
       4:   
       5:          String password = req.getParameter("password");
       6:   
       7:   
       8:          resp.setContentType("text/html;charset=gb2312");
       9:          PrintWriter out = resp.getWriter();
      10:   
      11:          if(username!=null && password!=null){
      12:              if(username.equals("admin") ){
      13:                  if( password.equals("123456"))
      14:                      out.println("Welcome admin come back."+"<br>");
      15:                  else
      16:                      out.println("Wrong admin password"+"<br>");
      17:   
      18:              }
      19:              else if(username.equals("张三") ){
      20:                  if( password.equals("1234"))
      21:                      out.println("Welcome 张三 come back."+"<br>");
      22:                  else
      23:                      out.println("Wrong 张三 password"+"<br>");
      24:              }
      25:   
      26:              else {
      27:                  out.println("Welcome "+username+" come back."+"<br>");
      28:              }
      29:          }
      30:   
      31:   
      32:      }

    web.xml

       1:  <?xml version="1.0" encoding="ISO-8859-1"?>
       2:   
       3:   
       4:  <web-app>
       5:   
       6:    <servlet>
       7:        <servlet-name>loginServlet</servlet-name>
       8:        <servlet-class>ServletWork01</servlet-class>
       9:    </servlet>
      10:    
      11:    
      12:    <servlet-mapping>
      13:        <servlet-name>loginServlet</servlet-name>
      14:        <url-pattern>/loginServlet</url-pattern>
      15:    </servlet-mapping>
      16:    
      17:  </web-app>

    QQ截图20130410202913

    输入地址如图,表单中填入数据,点submit就可以看到服务器 应用返回的结果了,这样就测试完了。

    小结:(摘抄他处)

    1、简单的说,get是通过http header来传输数据,有数量限制,而post则是通过http     body来传输数据,没有数量限制。

    2、你的表单提交都有方法的,如果指定method为get就调用get方法,用post就调用post方法. 在URL中get显示你传过去的参数,post则不显示.
    (把例子二的index.html中method改为get,在servlet的代码中实现doGet()就能测试)

    3、get方式有四种:1)直接在URL地址栏中输入URL。2)网页中的超链接。3)form中method为get。4)form中method为空时,默认是get提交。

    post只知道有一种:form中method属性为post。

    4、服务器接收方式

    服务器随机接受GET方法的数据,一旦断电等原因,服务器也不知道信息是否发送完毕

    而POST方法,服务器先接受数据信息的长度,然后再接受数据

    卸载最后:

    其实可以写一个servlet就可以实现get与post的测试,只需更改index.html中form的method方法为post或者get即可。

  • 相关阅读:
    luogu P4544 [USACO10NOV]Buying Feed G 斜率优化dp 双层?
    luogu P3594 [POI2015]WIL-Wilcze doły 单调队列dp+双指针
    luogu P2384 最短路 spfa+数学?
    luogu P2071 座位安排 二分图最大匹配 双重的
    luogu P1841 [JSOI2007]重要的城市 dp+Floyd
    luogu P2034 选择数字 单调队列优化dp 脑残行为,导致wa了很多遍
    【最短路-判断正权环 Floyd】Currency Exchange POJ
    【最短路-判断正权环 Bellman-Ford】Arbitrage POJ
    【最短路/矩阵+最小环】0 or 1 HDU
    【最短路+区间枚举】昂贵的聘礼 POJ
  • 原文地址:https://www.cnblogs.com/ppazhang/p/3013122.html
Copyright © 2020-2023  润新知