SpringMVC 引用BootStrap和jQuery

无心中在Maven公服中发现bootstrap经被打包到jar中了。javascript

http://mvnrepository.com/artifact/org.webjars/bootstrapcss

添加依赖
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>3.3.5</version>
</dependency>

在 bootstrap-3.3.5.pom 中的依赖只有一个
<dependencies>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>1.11.1</version>
    </dependency>
</dependencies>

基于xml的SpringMVC配置

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

基于Class的配置

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/welcome").setViewName("welcome");
        registry.addViewController("/readme").setViewName("readme");
        registry.addViewController("/login-page").setViewName("login");
        registry.addViewController("/logout/success").setViewName("logout_success");
        //
        registry.addRedirectViewController("/", "/welcome");
    }

}

引用

<!-- 新 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="${ctx}webjars/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- 可选的Bootstrap主题文件(通常不用引入) -->
<link rel="stylesheet" href="${ctx}webjars/bootstrap/3.3.5/css/bootstrap-theme.min.css">

<!-- jQuery文件。务必在bootstrap.min.js 以前引入 -->
<script src="${ctx}webjars/jquery/1.11.1/jquery.min.js"></script>

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="${ctx}webjars/bootstrap/3.3.5/js/bootstrap.min.js"></script>

thymeleaf

<!-- 新 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}" />

<!-- 可选的Bootstrap主题文件(通常不用引入) -->
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap-theme.min.css}" />

<!-- jQuery文件。务必在bootstrap.min.js 以前引入 -->
<script type="text/javascript" th:src="@{/webjars/jquery/1.11.1/jquery.min.js}"></script>

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script type="text/javascript" th:src="@{/webjars/bootstrap/3.3.5/js/bootstrap.min.js}"></script>