springspring-mvcmappinghttp-status-code-404static-resource

How to Configure Servlet Mapping and Resource Handler in Spring MVC


I have created sample Spring MVC REST Maven project with following folder structure Folder structure

ResourceHandlerRegistry configuration as follows

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.raju.spring_app")
public class RootConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static_res/*").addResourceLocations("/WEB-INF/html/static_res/");
    }
//Other methods 
}

Servlet mapping as follows

public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/", "/static_res/*" };
    }
    //Other Methods
}

The problem is whenever I tried to access resource http://localhost:8080/spring4_rest_angular_demo/static/css/app.css

I got 404 error. I want to keep this folder structure to get css IntelliSense suggestions in index.jsp file.

<link href="static_res/css/app.css" rel="stylesheet"></link>

Solution

  • Few corrections :

    Replace

    return new String[] { "/", "/static_res/*" };

    with

    return new String[] { "/" };

    and

    registry.addResourceHandler("/static_res/*")

    with

    registry.addResourceHandler("/static_res/**")

    Also, the right path is

    http://localhost:8080/spring4_rest_angular_demo/static_res/css/app.css

    and not

    http://localhost:8080/spring4_rest_angular_demo/static/css/app.css