Search code examples
servletshttp-status-code-404url-pattern

How to get correct URL for Java Servlet?


I'm working on a web based project where I have to pass data from JavaScript to a Java s Servlet with the following request:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'DCCServlet?command=' + encodeURIComponent(command), true);
xhr.send(null);

Here is the code for the Servlet: package web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DCCServlet extends HttpServlet{

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException{

        String command = request.getParameter("command");

         System.out.println(command);
         //Send string where it is needed
         Startup.MC.sendCommand(command);
    }   
}

And here is the 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>PiRail</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <listener>
    <listener-class>
             web.Startup
        </listener-class>
   </listener>

   <servlet>
        <servlet-name>DCCServlet</servlet-name>
        <servlet-class>web.DCCServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>DCCServlet</servlet-name>
        <url-pattern>/DCC</url-pattern>
    </servlet-mapping>

</web-app>

From what I can tell, there are no problems with the servlet, although I could be wrong. For whatever reason, every time I perform the action that makes the request, I get a 404 error in the Opera console.

GET http://localhost:8080/PiRail/DCCServlet?command=func%2044%204 404 (Not Found)

I'm guessing that I'm getting the URL wrong but I really don't know. If that's the case, what should the correct URL be and if not, what could be the problem?


Solution

  • In the xml in my opinion you've mapped the servlet at "/DCC" but you're requesting "/DCCServlet" in the GET