gpt4 book ai didi

java - 尝试调用 servlet 时遇到错误 404

转载 作者:行者123 更新时间:2023-11-28 22:45:14 25 4
gpt4 key购买 nike

我正在尝试使用 apache tomcat 7.0 tomcat7 访问 java servlet。

我在 webapps 的 ROOT 文件夹下创建了一个文件夹来保存我所有的 webapp 文件。文件结构是这样的。

  • Tomcat 7.0/webapps/myWebApp
    • HelloHome.html
    • WEB-INF
      • web.xml
      • 类(class)
        • com
          • 培训
            • HelloServlet.java
            • HelloServlet.class

调用 servlet 使用了这个 web.xml 代码:

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app version="3.0"
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">

<!-- To save as "hello\WEB-INF\web.xml" -->

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.training.HelloServlet</servlet-class>
</servlet>

<!-- Note: All <servlet> elements MUST be grouped together and
placed IN FRONT of the <servlet-mapping> elements -->

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>

</web-app>

实际java代码(在classes文件夹下编译生成class文件):

//To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\HelloServlet.java"
package com.training;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

// Set the response MIME type of the response message
response.setContentType("text/html");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();

// Write the response message, in an HTML page
try {
out.println("<html>");
out.println("<head><title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body></html>");
} finally {
out.close(); // Always close the output writer
}
}
}

然后我点击:http://localhost:8080/myWebApp/sayhello
并得到 404 错误。关于我做错了什么有什么想法吗?

最佳答案

myWebApp 应该位于 ROOT 旁边,而不是里面。

Tomcat 7 Deployment

关于java - 尝试调用 servlet 时遇到错误 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8033268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com