Search code examples
javaspringspring-mvcwebjetty

Serve HTML files from inside WAR file with Jetty server and Spring MVC


I have a simple Jetty server installation and run a WAR file compiled with Spring MVC. The WAR file is located in the $JETTY_BASE directory. jsp module is installed (java -jar $JETTY_HOME/start.jar --add-to-start=jsp) and JSP files are served well from inside the WAR file. But when I create a controller:

@Controller
@RequestMapping("/html")
public class HtmlHelloController {

    @RequestMapping("/hello")
    public String getHtmlHello() {
        return "/html/htmlHello.html";
    }
}

And try to use it with http://localhost:8080/web-app-spring/html/hello I get:

Mar 20, 2023 2:06:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /web-app-spring/html/htmlHello.html

The file html/htmlHello.html is present in my webapp directory.

Is there a (preferably simple) way to serve this html/htmlHello.html file from inside my WAR file in Jetty?


Solution

  • You have to enable Spring to serve up static files. All you did was tell Spring to return a "view" called "/html/htmlHello.html".

    You don't say what version of Spring you're using, but for instance with the latest: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-config-static-resources

    Here's the XML-based setup we use:

        <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static
            resource requests to the container's default Servlet -->
        <mvc:resources mapping="/resources/**" location="/htdocs/"/>
        <mvc:default-servlet-handler />