如何将css和js添加到spring启动应用程序中?

Ham*_*dwn 4 spring thymeleaf spring-boot

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

<link rel="stylesheet" th:href="@{/css/home.css}" href="../../css/home.css" />
Run Code Online (Sandbox Code Playgroud)

但它不起作用.


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

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

任何人都可以告诉我什么是我的错误或是否需要任何配置?

Dan*_* C. 14

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

例如:

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

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

<link th:href="@{/css/style.css}" rel="stylesheet" />
Run Code Online (Sandbox Code Playgroud)

这里只是一个观察,如果您正在使用@EnableWebMvc注释,那么您应该通过自己的配置映射静态资源.

编辑

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

所有的资源应该从浏览器进行访问,否则.css.js不会被加载.

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

  1. 转到该/resources/static文件夹并创建两个子文件夹,一个用于匿名用户的资源public,另一个用于经过身份验证的用户private.
  2. 将所有公共资源放入该 /resources/static/public文件夹.
  3. 将所有私有资源放入该 /resources/static/private文件夹.
  4. 转到Spring安全配置类并/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()

        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后尝试访问公共资源,例如,如果您style.css在公共文件夹下有文件,然后尝试访问它:http://localhost:808/public/style.css,浏览器应显示style.css内容.

当您尝试访问私人文件夹(没有身份验证)时,例如私有文件夹下有一个private.css,然后尝试:http://localhost:808/private/private.css.您应该被重定向到登录页面,这意味着您应该首先登录,在那个春天之后将允许您访问private.css资源.

关于百里香,这是相同的方法,因为公共html页面使用公共资源:<link th:href="@{/public/public.css}" rel="stylesheet" />和受保护资源用户私人索取<link th:href="@{/private/syle.css}" rel="stylesheet" />