如何在 Spring MVC 中配置 Servlet 映射和资源处理程序

How to Configure Servlet Mapping and Resource Handler in Spring MVC

我已经创建了具有以下文件夹结构的示例 Spring MVC REST Maven 项目

ResourceHandlerRegistry配置如下

@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映射如下

public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

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

问题是每当我尝试访问资源时 http://localhost:8080/spring4_rest_angular_demo/static/css/app.css

我收到 404 错误。 我想保留此文件夹结构以获得 css IntelliSense 建议 在 index.jsp 文件中。

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

使用 Spring 3.0.4.RELEASE 及更高版本,您可以使用

<mvc:resources mapping="/resources/**" location="/public-resources/"/>

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-static-resources

此外,您应该避免将页面放在 WEB-INF 中。将层次结构 html/css/js 的文件夹放在 web app 文件夹下。通常,在 WEB-INF 中应该只有配置 xml 个文件。

少量更正:

替换

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

return new String[] { "/" };

registry.addResourceHandler("/static_res/*")

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

另外,正确的路径是

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

而不是

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