doPost和doGet方法的区别

来源:互联网 发布:mac os 10.12 qq截图 编辑:程序博客网 时间:2024/05/18 01:30

新建一个Servlet,代码如下(刚进入程序的时候,调用的是doGet方法),首先要明白servlet的原理,一次请求过来的时候,首先调用的是service方法,然后根据你的form表单是post则调用doPost()方法,get则调用doGet()方法,如果不写,默认为doGet方法,所以,一般情况下,doGet()和doPost()是有一个要被执行的:

package com.busymonkey;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;import javax.servlet.Servlet;public class Test1 extends HttpServlet implements Servlet {    /** *  */private static final long serialVersionUID = 1L;public Test1() {        super();    }    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        this.log("执行doGet()方法... "); // 调用Servlet自带的日志输出信息到控制台        this.execute(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        this.log("执行doPost()方法... "); // 调用Servlet自带的日志输出信息到控制台        this.execute(req, resp);    }    public void execute(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        resp.setCharacterEncoding("UTF-8"); // 设置resp的编码格式        req.setCharacterEncoding("UTF-8"); // 设置resp的编码格式        String reqURL = req.getRequestURI();// 设置访问该Servlet的URL        String method = req.getMethod(); // 设置访问Servlet的方法,GET或POST        String param = req.getParameter("param");// 设置客户端提交的参数param的值        resp.setContentType("text/html"); // 设置文档类型为HTML        PrintWriter out = resp.getWriter();        out.println("<!DOCTYPE HTML PUBLIC\" -//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<html>");        out.println("<head><title>A Servlet</title></head>");        out.println("<body>");        out.println("以" + method + "方式访问该页面,取到的param参数为:" + param + "<br/>");        out.println("<form action='"                        + reqURL                        + "' method='get'><input type='text' name='param' value='param String'><input type='submit' value='以get方式查询界面"                        + reqURL + "'></form>");        out.println("<form action='"                        + reqURL                        + "' method='post'><input type='text' name='param' value='param String'><input type='submit' value='以post方式查询界面"                        + reqURL + "'></form>");        // 有客户端浏览器读取该文档的更新时间        out.println("<script>document.write('本页面最后的更新时间:'+ document.lastModified);</script>");        out.println("</body>");        out.println("</html>");        out.flush();        out.close();    }}


1 0
原创粉丝点击