【问题标题】:Spring MVC with Thymeleaf + Bootstrap using webjars使用 webjars 的带有 Thymeleaf + Bootstrap 的 Spring MVC
【发布时间】:2017-05-23 18:00:36
【问题描述】:

我有一个 Spring 项目,其中我将以下 webjar 包含到 pom.xml 中:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>3.3.7-1</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.1.1</version>
</dependency>

然后我在我的 HTML 视图中包含以下链接和脚本:

<link rel="stylesheet" href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />

<script src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>

但它不起作用,没有找到映射:

[org.springframework.web.servlet.PageNotFound] (default task-15) No mapping found for HTTP request with URI [/TestPublicWeb-0.0.1-SNAPSHOT/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css] in DispatcherServlet with name 'testapp'

...所以我尝试在servlet.xml 中包含以下映射:

<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

但是有了这个,我的/TestApplication 的映射就找不到了:

[org.springframework.web.servlet.PageNotFound] (default task-13) No mapping found for HTTP request with URI [/TestApplication/] in DispatcherServlet with name 'testapp'

webjars应该如何以正确的方式包含在Spring项目中?

【问题讨论】:

    标签: java jquery twitter-bootstrap spring-mvc thymeleaf


    【解决方案1】:

    关于为什么上述内容不适合您,我可以想到几件事。确保您在 servlet.xml 文件中使用 spring mvc 命名空间。看起来像:

    <bean xmlns:mvc="http://www.springframework.org/schema/mvc"....
    

    当您指定类路径时,也不确定为什么要尝试使用@{..} 访问资产。尝试像这样删除@{..}

    <link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
    
    <script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
    <script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
    

    【讨论】:

      【解决方案2】:

      问题是您将标准 HTML href 标记与 Thymeleaf 的语法 @{} 混合在一起。修改如下:

      <link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
      
      <script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
      <script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
      

      如果您使用 Spring Security,您还需要在 configure(HttpSecurity http) 方法中指定对 webjars 的授权,例如:

      http.authorizeRequests().antMatchers("/webjars/**").permitAll();
      

      【讨论】:

        猜你喜欢
        • 2018-08-15
        • 2018-06-19
        • 2018-08-05
        • 1970-01-01
        • 2020-01-31
        • 2016-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多