龑凯

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

什么情况下调用doGet()和doPost()?
Jsp页面中的form标签里的method属性为get时调用doGet(),为post时调用doPost()

测试方法如下:
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>get</h1>
<!-- 绝对路径路径访问  <form action="http://localhost:8080/untitled/myServlet" method="get">-->
<!-- 绝对路径访问—省略写法     <form action="/untitled/myServlet" method="get">-->
<form action="myServlet" method="get"><!--相对路径访问  省略了 ./-->
    <input type="submit">
</form>

<h1>post</h1>
<form action="http://localhost:8080/untitled/myServlet" method="post">
    <input type="submit">
</form>

</body>
</html>

MyServlet实现类

@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get方法");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("set方法");
    }

}

总结:

默认情况是调用doGet()方法,JSP页面中的Form表单的method属性设置为post的时候,调用的为doPost()方法;为get的时候,调用deGet()方法。





posted on 2021-01-02 17:37  龑凯  阅读(412)  评论(0编辑  收藏  举报