【问题标题】:How to Configure Servlet Mapping and Resource Handler in Spring MVC如何在 Spring MVC 中配置 Servlet 映射和资源处理程序
【发布时间】:2016-03-12 19:46:52
【问题描述】:

我创建了具有以下文件夹结构的示例 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>

【问题讨论】:

  • 感谢@BalusC 的更正。

标签: spring spring-mvc mapping http-status-code-404 static-resource


【解决方案1】:

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 应用程序文件夹下。一般WEB-INF中应该只有配置xml文件。

【讨论】:

  • 1) 他正在使用与您发布的代码等效的 Java 配置。 2) 您应该将资源放在 WEB-INF 之外,但 JSP 应该保留在 WEB-INF 文件夹中。这样,客户端将无法直接访问它 - 它应该由控制器提供服务。
【解决方案2】:

一些更正:

替换

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 2015-02-26
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多