servlet中的doPost方法没有被调用

时间:2018-12-02 11:33:50

标签: java servlets

我正在尝试覆盖doGet和doPost,并尝试调用doPost,但无法正常工作。下面是JSP和Servlet代码

    <%@ page language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form method="post" action="FirstServlet">

<input type="text" name="Name" value="Enter">
<input type="button" name="submit" value="Submit"/>
</form>
</body>
</html>

并且Servlet代码在下面,并尝试调用doPost方法,但未调用它,也不在控制台中打印消息。但是,当我尝试直接从URL访问servlet时,就会调用doGet方法

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FirstServlet
 */
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FirstServlet() {
        super();
        System.out.println(" Inside Constructor");
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println(" Inside init");
    }


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println(" Inside doGet");
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println(" Inside doPost");
        doGet(request, response);
    }
}

1 个答案:

答案 0 :(得分:1)

您的HTML表单提交按钮不正确:修复了 type 属性。 试试:

<input type="submit" name="submit" value="Submit"/>