一尘不染

尝试运行servlet时出现HTTP Status 404错误

tomcat

我尝试运行的简单servlet Hello.java有问题。我将其制作在eclipse中,然后将其放在文件webapps/ServletTest/WEB- INF/classes夹中并进行编译,然后Hello.class在同一文件夹中创建文件。然后,我修改了web.xml文件以映射servlet,并尝试通过以下地址运行它

http://localhost:8080/ServletTest/Hello

但是,这不起作用,出现以下错误

HTTP状态404-

类型状态报告

信息

描述所请求的资源不可用。 Apache Tomcat / 7.0.42

web.xml文件中的映射如下所示:

<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>Main.Hello</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>

servlet的代码:

package Main;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Hello")
public class Hello extends HttpServlet {
private static final long serialVersionUID = 1L;
public Hello() {
super();
 }

protected void doGet(HttpServletRequest request, HttpServletResponse

response)  throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    String path = request.getContextPath();
    String ip = request.getRemoteAddr();
    out.print("<html>" +
    "<title>Hello</title>" +
            "Hello World"+ "<br>" +
    "Your ip is: " + ip + "<br>" +
    "Your path is: " + path
    + "</html>");       
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws     ServletException, IOException {

}

}

阅读 625

收藏
2020-06-16

共1个答案

一尘不染

编译后的Hello.class文件应该在文件夹中

webapps/ServletTest/WEB-INF/classes/Main

因为它被声明在package中Main

此外,你可以看到Tomcat的启动日志中/logs/catalina.out/logs/catalina.log根据。


另外,Suresh在注释中是正确的,请使用<servlet>声明或@WebServlet。请勿同时使用。

2020-06-16