【发布时间】:2014-07-26 08:13:53
【问题描述】:
(已解决!)
我正在关注有关 servlet 的教程,但我很早就陷入困境。出于某种原因,一旦调用控制器(下面的 Controller.java),我就会得到 404。
这个想法是 index.jsp 中的表单应该调用一个控制器 (form action="Controller") 以确定应该将表单中的信息发送到哪个页面,具体取决于按下了表单中的哪个按钮(目前只有一个,confirmButton)。
但是,当调用 Controller 时,我不断收到 404。
...帮助?
index.jsp
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Simple Edit Page</title>
</head>
<body>
<p>This is a simple HTML page that has a form in it.
<form action="Controller">
<p>
If there is a value for the hobby in the query
string, then it is used to initialize the hobby
element.
<p>
Hobby: <input type="text" name="hobby"
value="${param.hobby}">
<input type="submit" name="confirmButton"
value="Confirm">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>controller.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/controller/Controller</url-pattern>
</servlet-mapping>
</web-app>
Controller.java
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String address;
if (request.getParameter("processButton") != null) {
address = "Process.jsp";
} else if (request.getParameter("confirmButton") != null) {
address = "Confirm.jsp";
} else {
address = "index.jsp";
}
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
文件放置:
src/controller/Controller.java
web/WEB-INF/classes/controller/Controller.class
【问题讨论】:
-
Servlet 很痛苦。对不起。
-
您的表单中没有提交方法。添加
<form method="POST">!