无法调用servlet post方法

时间:2014-12-30 09:31:34

标签: jsp servlets post

我想调用doLogOut servlet的post方法,但每次调用servlet时,都会调用Get方法而不是post方法!< / p>

这是我的jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Checkout </title>
    </head>
    <body>
        <form method="post" action="doLogOut">
            <p style="text-align: right;">
                <a href="doLogOut"> LogOut </a>
            </p>
        </form>
         ...
</html>

这是我的doLogOut servlet:

@WebServlet(urlPatterns = {"/doLogOut"})
public class doLogOut extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet doLogOut</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3> Get method: </h3>");
        out.println("</body>");
        out.println("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet doLogOut</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3> Post method: </h3>");
        out.println("</body>");
        out.println("</html>");
    }
}

但我在结果中看到Get method:消息,为什么?

2 个答案:

答案 0 :(得分:1)

单击<a href="..." />默认执行GET请求。您应该使用POST方法提交表单或执行ajax请求。这是一个描述这个想法的例子:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <title> Checkout </title>
        <script type="text/javascript">
        function logoutWithAjax() {
            $.ajax({
              type: "POST",
              url: "doLogOut",
              success: function() {
                console.log("Logged out");
              }
            });
        }
        </script>
    </head>
    <body>
        <form id="form" method="post" action="doLogOut">
            <p style="text-align: right;">
                <a href="javascript:{}" onclick="document.getElementById('form').submit();"> LogOut with Form Submit</a>
                <a href="javascript:{}"  onclick="logoutWithAjax();"> LogOut with Ajax Request</a>
            </p>
        </form>
    </body>
</html>

答案 1 :(得分:1)

您可以尝试使用bootstrap的按钮类btn-link,以便将提交按钮用作链接。

<form method="post" action="doLogOut">
     <p style="text-align: right;">
          <button type="submit" class="btn-link"> LogOut </button>
     </p>
<form>