我正在尝试执行一个 servlet 程序,该程序选择一种颜色并通过 servet 显示它。我已经正确配置了 tomcat 服务器。但是当我尝试运行代码时,index.HTML 文件正常打开但是当我单击提交按钮时,它应该打开我的 servlet 文件,它将显示我选择的颜色。但是,而不是让我的 servlet 我收到 404 错误。这是下面给出的代码。有什么建议吗?
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The Selected Color is:");
pw.println(color);
}
}
这是我的html文件
<html>
<head>
<title> </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8084/ServletExample/ColorGetPost">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
当我运行这个程序时,我得到了可以选择颜色的页面:
但在点击提交按钮后我收到 404 错误。
servlet 的 xml 文件
<servlet>
<servlet-name>ColorPostServlet</servlet-name>
<servlet-class>ServletExample.ColorPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorPostServlet</servlet-name>
<url-pattern>/ColorPostServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
最佳答案
您的表单有错误的操作 url。
<form name="Form1"
method="post"
action="http://localhost:8084/ServletExample/ColorGetPost">
它应该指向 servlet url:
<form name="Form1"
method="post"
action="http://localhost:8084/ServletExample/ColorPostServlet">
基本上:action="http://localhost:[Port]/[ProjectName]/[ServletName]"
关于java - 无法连接到 Netbeans 中的 servlet 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677159/