简体   繁体   中英

404 Error on running a simple class that extends HTTPServlet

The following code is my web.xml file :

<?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>

The following code is a simple class that extends the HTTPServlet class:

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");

}

}

When I try to run this code on Tomcat 7, it's displaying the following error message:

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"

Can someone please tell me what's wrong with this code? And please suggest how I can successfully run this.

You must call the url

http://yourHost/MySimpleServletProject/xmlServletpath/

and not the servlet-class that you've configured.

Here, while you are trying to access your Servlet via url.. The url-mapping you have done in your web.xml must map with the url you have typed in the browser..

Thus after the localhost definition, you should provide the context path and then follow with the url you have given in between the <url-pattern> tags in web.xml !

So, the url would be like

localhost:8084/MySimpleServletProject/xmlServletpath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM