java - Spring Boot 2 中的映射资源

标签 java css spring-boot spring-mvc spring-security

我正在使用 Spring Boot 2.2.2.RELEASE 来服务网络,并希望允许每个用户使用我的页面的静态内容,例如 css未经验证的。

enter image description here

据我了解,static文件夹下的资源被映射到根目录,因此访问localhost:8080/css/sobre.css我应该访问我的css文件。但我却被重定向到登录页面。

这没关系,我知道在 Spring Boot 1.5 中,默认情况下允许使用 static 下的资源,但是 changed .

因此,我使用自定义 WebSecurityConfigurerAdapter 来允许该路径,因此它看起来像:

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/login*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .and()
                .logout()
                .logoutUrl("/perform_logout")
                .deleteCookies("JSESSIONID");
    }

但是当我转到包含资源链接的页面时,我得到:

No mapping for GET /css/sobre.css

enter image description here

将每个资源都映射到实际文件中并不是正确的方法。

所以我真的不知道该怎么做。我缺少什么?我只想:

 <link rel="stylesheet" href="/css/sobre.css" />

谢谢。

最佳答案

我必须做三件事:

  • 从主类中删除 @EnableWebMvc

  • 在安全适配器中添加该路径的异常(exception):

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**");
    }
    

    或与HttpSecurity:

    .antMatchers("/css/*").permitAll()
    
  • 如果您的静态文件夹不名为“static”,请将根路径设置为资源文件夹:

    spring.resource.static-locations=“classpath:/publicfiles/”

关于java - Spring Boot 2 中的映射资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60571890/

相关文章:

javascript - IE 的 CSS 悬停属性替代方案

css - 不能用 css 居中三个 div

java - 如何解决这种拒绝服务问题的可能性?

Spring Cloud Config Server 配置与本地存储库

java - 无法运行 Spring Boot 测试应用程序

java - 如何在java中接受来自用户的不同数据类型

java - 如何限制rest api方法的列表参数中的值

javascript - Kendo ui 条形图宽度/条形的最大宽度

java - 无法运行 griffon 应用程序

java - 确认字符串中存在按顺序排列的字符范围