Cherry
Cherry

Reputation: 33544

How to make spring serve a static html file?

I have created Spring application without web.xml. And I want to serve a static index.html from WEB-INF. Here are the sources:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {return new Class<?>[]{AppConfiguration.class};}

    @Override
    protected Class<?>[] getServletConfigClasses() {return new Class[]{WebConfiguration.class};}

    @Override
    protected String[] getServletMappings() {return new String[]{"/ololo/*"};}
}

import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfiguration {}


@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/index.html").addResourceLocations("classpath:/WEB-INF/view/index.html");
    }
}

Everything seem to be correct - index.html is placed into webapp\WEB-INF\view\index.html, but I still get in logs (contextRoot is context root for my deployed war):

[2015-09-11T11:06:21.247+0500] [glassfish 4.1] [WARNING] [] [org.springframework.web.servlet.PageNotFound] [tid: _ThreadID=29 _ThreadName=http-listener-1(3)] [timeMillis: 1441951581247] [levelValue: 900] [[
  No mapping found for HTTP request with URI [/contextRoot/ololo/index.html] in DispatcherServlet with name 'dispatcher']]

What is wrong with configuration?

UPDATED

Path in Spring is big problem when something goes wrong, so any advices about spring debugging in context of dispatching requests or where I can see configuration instantiation are welcome.

Upvotes: 2

Views: 5111

Answers (1)

GUISSOUMA Issam
GUISSOUMA Issam

Reputation: 2582

Try the code below, I have a working example

@Configuration
@EnableWebMvc
@ComponentScan("com.Your.Package")//in my case com.igu
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }
}

Put your static html files(index.html) in webapp/static/

Which would pass through all requests starting with /static/ to the webapp/static/ directory.

project

browser

Upvotes: 5

Related Questions