手记

实验一 区分Servlet中Get和Post请求处理方法

  1. 新建工程


  2. 新建Servlet类
  3. Eclipse已经帮助我们在web.xml中配置好
  4. 新建html文件,命名为login.html
  5. login.html代码如下:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="Test" method="get">
        <input type="text" name="test1"/>
        <input type="submit" value="submit"/>
    </form>
    <hr/>
    <form action="Test" method="post">
        <input type="text" name="test2"/>
        <input type="submit" value="submit"/>
    </form>
    </body>
    </html>
  6. Test.java的代码为:
    
    package com;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
  7. Servlet implementation class Test
    */
    public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**

    • @see HttpServlet#HttpServlet()
      */
      public Test() {
      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.getWriter().append("Served at: ").append(request.getContextPath());
      PrintWriter writer = response.getWriter();
      writer.println("this is the Get method.test1="+request.getParameter("test1"));
      }

    /**

    • @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);
      PrintWriter writer = response.getWriter();
      writer.println("this is the Post method.test2="+request.getParameter("test2"));
      }
      }
  8. 结果:


    由实验可知get和post方法的不同。
3人推荐
随时随地看视频
慕课网APP