【问题标题】:how add css and js to spring boot application?如何将 css 和 js 添加到 Spring Boot 应用程序中?
【发布时间】:2018-01-14 04:09:25
【问题描述】:

我尝试使用 Thymeleaf 在 Spring Boot 中将 CSS 添加到我的 HTML 页面,将 CSS 文件添加到静态文件夹并以这种方式链接:

<link rel="stylesheet" th:href="@{/css/home.css}" href="../../css/home.css" />

但它不起作用。


我想停止访问 URL 中的 CSS 和 js,所以我将此方法添加到我的安全配置中:

@Override
public void configure(WebSecurity web) throws Exception {
   web
      .ignoring()
      .antMatchers("/resources/static/**"); // #3
}

谁能告诉我我的错误是什么或者是否需要任何配置?

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

    .css.js 是静态资源,Spring Boot 默认将其映射到您的 /resources/static 文件夹中

    例如:

    有一个style.css 文件位于/resources/static/css/style.css

    如果您想通过 thymeleaf 访问它,请将其添加到您的 html 头部部分:

    <link th:href="@{/css/style.css}" rel="stylesheet" />
    

    这里只是一个观察,如果你使用@EnableWebMvc注解,那么你应该通过你自己的配置来映射静态资源。

    编辑

    我想停止访问 URL 中的 CSS 和 js,所以我将此方法添加到我的安全配置中

    所有资源都应该从浏览器访问,否则.css.js将不会被加载。

    如果您只需要通过身份验证的用户访问资源,您可以尝试以下配置:

    1. 转到/resources/static 文件夹并创建两个子文件夹,一个用于匿名用户public 的资源,另一个用于经过身份验证的用户private
    2. 将所有公共资源放到/resources/static/public文件夹中。
    3. 将所有私有资源放到/resources/static/private文件夹中。
    4. 转到您的 Spring Security 配置类并使用此配置将您的 /private url 设为私有:.antMatchers( "/private/**").authenticated() 并使 /public 可供匿名用户访问:.antMatchers( "/public/**").permitAll()

    安全配置示例:

      @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers( "/public/**").permitAll()
                    .antMatchers( "/private/**").authenticated()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll()
    
            ;
        }
    }
    

    最后尝试访问公共资源,比如你的public文件夹下有style.css文件,然后尝试访问:http://localhost:808/public/style.css,浏览器应该会显示style.css内容。

    当您尝试访问私有文件夹时(无需身份验证),例如私有文件夹下有一个 private.css 则尝试:http://localhost:808/private/private.css。你应该被重定向到登录页面,这意味着你应该先登录,然后春天会让你访问private.css资源。

    对于 thymeleaf,它是相同的方法,对于公共 html 页面使用公共资源:&lt;link th:href="@{/public/public.css}" rel="stylesheet" /&gt;,对于受保护资源,用户私有资源 &lt;link th:href="@{/private/syle.css}" rel="stylesheet" /&gt;

    【讨论】:

    • 如果要使用标签th,则必须将&lt;html&gt;替换为&lt;html xmlns:th="http://www.thymeleaf.org"&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2019-04-26
    相关资源
    最近更新 更多