0
我在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
。
這很奇怪?您如何獲取用戶名和密碼 – 2013-03-04 07:29:51
您是否使用JSP文件進行了測試以確認參數正在POST?否則,你可以嘗試request.getParamterMap來查看所有傳遞的參數。 – Rhys 2013-03-04 07:31:49