【发布时间】:2011-12-23 09:54:35
【问题描述】:
我正在尝试使用 apache tomcat 7.0 tomcat7 来访问 java servlet。
我创建了一个文件夹来保存我所有的 webapp 文件在 webapps 的 ROOT 文件夹下。 文件结构是这样的。
- Tomcat 7.0/webapps/myWebApp
- HelloHome.html
- WEB-INF
- web.xml
- 类
- com
- 培训
- HelloServlet.java
- HelloServlet.class
- 培训
- com
使用这个 web.xml 代码调用 servlet:
<?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文件夹下的类文件):
//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 错误。关于我做错了什么有什么想法吗?
【问题讨论】:
-
您的 servlet 不能在默认包中。将其放入一个包中,使用新的包信息更新您的 web.xml。
-
将我的类文件放在一个包中。类 -> com -> 培训 -> HelloServlet.class。还将 web.xml 文件的
标记更新为 com.training.HelloServlet 。仍然是 404 错误。 -
问题中的目录结构完全不清楚:请通过使其等宽和正确缩进来修复它,使其清晰可见。
-
web.xml 中关于分组的注释不正确,顺便说一句。
-
编辑了目录结构和 web.xml
标签。
标签: java apache jsp tomcat servlets