我在Tomcat 7上部署了我的简单java Web应用程序,但是出了点问题。
当我使用方法POST
将表单提交给servlet时,tomcat实际上会按预期调用doGet()
而非doPost()
。
这是我的代码:
的index.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
。
答案 0 :(得分:0)
问题解决了:)。谢谢你的评论。
我使用Netbeans部署我的Web应用程序,它会自动部署我过去为我开发的其他无关应用程序。在我将Maven命令mvn clean
应用于所有这些不相关的Web项目后,它按预期工作。