0

我在 Tomcat 7 上部署了我的简单 Java Web 应用程序,但出现了问题。

当我使用 method 将表单提交给 servlet 时POST,tomcat 实际上调用的doGet()不是doPost()预期的。这是我的代码:

索引.html:

<html>
    <body>
        <form action="http://localhost:8084/authentication" method="post">
            <input type="text" name="username">
            <input type="password" name="password">
            <input type="submit">
        </form>
    </body>
</html>

AuthenticationServlet.java:

public class AuthenticationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        response.sendError(405, "Method GET is not allowed");
    }

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        // unreachable
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username == null || password == null) {
            response.sendError(400, "username and password are required");
            return;
        }

        ...
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>foo.bar.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <servlet>
        <servlet-name>authentication</servlet-name>
        <servlet-class>foo.bar.AuthenticationServlet</servlet-class>
    </servlet>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <servlet-name>authentication</servlet-name>
    </filter-mapping>
    <servlet-mapping>
        <servlet-name>authentication</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

后来我doGet()改成

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

虽然我在表单中输入了用户名和密码,但用户名和密码是null.

4

1 回答 1

0

问题已经解决了:)。并感谢您的评论。

我使用 Netbeans 部署我的 Web 应用程序,它会自动部署我过去为我开发的其他不相关的应用程序。在我将 Maven 命令mvn clean应用于所有这些不相关的 Web 项目后,它按预期工作。

于 2013-03-04T09:51:40.673 回答