Search code examples
javaxmlresttomcathttp-status-code-404

Tomcat error 404 not found while running a REST API


I am trying to implement a very simple REST API in Eclipse.

Following is my project Structure: project Structure

Hello.java:

package test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@Path("/hello")
public class Hello {

    @GET
    @Produces(MediaType.TEXT_XML)
    public String sayHelloXML() {
        String responseString = "<? xml version='1.0' ?>" + 
                "<hello> Hello World XML</hello>";
        
        return responseString;
    }
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String sayHelloJSON() {
        String responseString = null;
        return responseString;
    }
    
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String sayHelloHTML() {
        String responseString = "<h1> Hello World HTML</h1>";
        return responseString;
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>JavaApiEdu</display-name>
  
  <servlet>
    <servlet-name>JAVA API</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer.class</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>test</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>JAVA API</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

To Run, I right-click on the project and choose Run on Server which is Tomcat 8.5. I am unable to access this and see this page: Error


Solution

  • After struggling a lot there are generally small things that solve the issues.

    I did two things:

    1. I removed the .class from this servlet class name in my web.xml and it started working: web.xml
    2. I also gave a path to all my methods as GyuHyeon suggested. Although if I don't do this then also it's working after doing step 1. It will just go to one of the methods as opposed to a specific one. Giving path to each method is a good step to follow.

    Note: to access the API the project name should be in the URL and not the package, so in my case, this worked: http://localhost:8080/JavaApiEdu1/hello/html

    Thanks @GyuHyeonChoi & @tgdavies for replying.