以下代码是我的web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MySimpleServletProject</display-name>
<servlet>
<servlet-name>xmlServlet</servlet-name>
<servlet-class>myServletPackage.XmlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xmlServlet</servlet-name>
<url-pattern>/xmlServletpath</url-pattern>
</servlet-mapping>
</web-app>
以下代码是一个扩展HTTPServlet类的简单类:
package myServletPackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class XmlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Msg from 'XmlServlet' class");
}
}
当我尝试在Tomcat 7上运行此代码时,它显示以下错误消息:
HTTP Status 404 - /MySimpleServletProject/servlet/myServletPackage.XmlServlet
--------------------------------------------------------------------------------
type Status report
message /MySimpleServletProject/servlet/myServletPackage.XmlServlet
description The requested resource (/MySimpleServletProject/servlet/myServletPackage.XmlServlet) is not available.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.12"
有人可以告诉我这段代码有什么问题吗?请建议我如何成功运行。
答案 0 :(得分:1)
您必须拨打网址
http://yourHost/MySimpleServletProject/xmlServletpath/
而不是您已配置的servlet-class
。
答案 1 :(得分:0)
在这里,当你试图通过url访问你的Servlet时..你在web.xml中完成的url-mapping必须映射你在浏览器中输入的url ..
因此,在localhost定义之后,您应该提供上下文路径,然后使用您在web.xml中的<url-pattern>
标记之间给出的URL!
所以,网址就像
localhost:8084/MySimpleServletProject/xmlServletpath