java - 无法连接到 Netbeans 中的 servlet 文件

标签 java tomcat servlets

我正在尝试执行一个 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>

当我运行这个程序时,我得到了可以选择颜色的页面:

screenshot

但在点击提交按钮后我收到 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>

my app "ServletExample"

最佳答案

您的表单有错误的操作 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/

相关文章:

java - 如何在特定包中获取带有某些注释的类

java - 如何一次将一个值存储到哈希表中。

java - 从 Spring Data JPA 查询方法返回自定义集合

java - 相同的图像,但不同的 base64

GWT 模块 'xyz' 可能需要(重新)编译

java - 在没有 web.xml 的情况下配置 servlet url-patterns

spring-boot - 在同一台服务器上运行服务器 Spring Boot 应用程序

java - 如何限制tomcat中的登陆页面?

java - 从 servlet 创建的 html 获取信息

java - 在Servlet中获取表单值