Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在启用安全性的Spring5中加载静态资源时出现问题_Java_Spring Boot_Spring Security_Thymeleaf_Mvc_Web Flux - Fatal编程技术网

Java 在启用安全性的Spring5中加载静态资源时出现问题

Java 在启用安全性的Spring5中加载静态资源时出现问题,java,spring-boot,spring-security,thymeleaf,mvc,web-flux,Java,Spring Boot,Spring Security,Thymeleaf,Mvc,Web Flux,我在加载静态资源(如图像、css样式等)时遇到问题。。。。在春季5中 当我添加安全性时,如果没有安全性,则加载ok 我就是这样做的 首先,我使用Eclipse中的Spring Starter项目创建了一个项目 弹簧启动版本:2.2.6 添加一些依赖项: 弹簧网 百里香 春季安全 弹簧靴开发工具 弹簧靴执行器 运行项目,我使用生成的安全密码,一切正常 现在我添加了statics资源 所以我创建了一个名为/assets/imgs的文件夹 在src/main/resources/static中/ 我在

我在加载静态资源(如图像、css样式等)时遇到问题。。。。在春季5中 当我添加安全性时,如果没有安全性,则加载ok

我就是这样做的

首先,我使用Eclipse中的Spring Starter项目创建了一个项目

弹簧启动版本:2.2.6

添加一些依赖项:

弹簧网

百里香

春季安全

弹簧靴开发工具

弹簧靴执行器

运行项目,我使用生成的安全密码,一切正常

现在我添加了statics资源

所以我创建了一个名为/assets/imgs的文件夹

在src/main/resources/static中/

我在那个文件夹中添加了一个假图像,名为fake-image.png

我创建了一个类,使用用户、密码和模式来允许我的资源

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
        .authorizeRequests().antMatchers("/resources/**", "/static/**","/src/main/resources/**").permitAll().and()
        .formLogin().loginPage("/login").permitAll()
        .usernameParameter("username").passwordParameter("password")
        .defaultSuccessUrl("/loginsuccess").permitAll().and()
        .logout().permitAll();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {

        PasswordEncoder encoder = passwordEncoder();
        UserBuilder users = User.builder().passwordEncoder(encoder::encode);

        //User to login
        builder.inMemoryAuthentication()
                .withUser(users.username("admin").password("q").roles("ADMIN"));

    }

}
我创建了一个类来添加我的登录表单

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/").setViewName("login");
    }

}
最后,我添加了一个类似这样的login.html页面,以显示一个简单的图像

<!DOCTYPE html>
<html lang="es" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<meta name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="" />
<meta name="author" content="" />

<meta name="ctx" th:content="@{/}" />

<title>Test Static Files</title>

</head>
<body>
    <div class="container">
        <div class="row no-gutters mt-3">
            <div class="col columna-banner">
                <img class="img-fluid rounded login-banner-image"
                    th:src="@{/assets/imgs/fake-image.png}" />
            </div>
        </div>
    </div>
</body>
</html>

测试静态文件
在eclipse控制台中,我收到以下警告消息:

警告1434---[nio-8080-exec-2]o.s.web.servlet.PageNotFound:GET/assets/imgs/fake-image.png没有映射

更新1:

向github添加了代码:

我错过什么了吗

有什么建议吗


谢谢

您是否在属性中配置了静态位置。
比如spring.resources.static location=classpath:/static/assets/imgs/

实际上需要知道/考虑三件事:

  • 构建(maven/gradle)

    无需进一步配置,
    sry/main/resources/
    文件夹的所有内容都将复制到您的“类路径根”(
    classpath://

  • (Url2Class)路径映射

    此属性:

    (值可以是(类路径)位置的逗号分隔列表。)

    如果您正在使用,这也很有趣:

    (意思是:从
    spring.resources.static locations
    /**
    的所有内容都映射到了
    /**

    …而不是:

    因此,到目前为止,了解“您的文件位于何处”以及它将映射/公开到哪个url是很重要的。 您可以选择以下选项:

  • (首选)符合预定义的位置
  • 重写
    spring.resources.static locations
    属性
  • (最不可取)引入“自定义映射/hadler”
  • 安全配置

    您的安全配置应该与(您希望允许的内容和)您希望提供的url(模式)保持一致。通常允许访问静态资源

  • @Configuration
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http
            .authorizeRequests().antMatchers("/resources/**", "/static/**","/src/main/resources/**").permitAll().and()
            .formLogin().loginPage("/login").permitAll()
            .usernameParameter("username").passwordParameter("password")
            .defaultSuccessUrl("/loginsuccess").permitAll().and()
            .logout().permitAll();
        }
    
        @Bean
        public BCryptPasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
    
            PasswordEncoder encoder = passwordEncoder();
            UserBuilder users = User.builder().passwordEncoder(encoder::encode);
    
            //User to login
            builder.inMemoryAuthentication()
                    .withUser(users.username("admin").password("q").roles("ADMIN"));
    
        }
    
    }
    

    关于OP:

    src/main/resources/static/assets/*
    在类路径上可用,并且(默认情况下)通过url
    /static/assets/*
    公开

    因此,请在html文件中更正为:
    th:src=“@{/static/assets/imgs/fake image.png}”
    。(现在404更容易理解了。)


    然后它应该与:
    .authorizeRequests().antMatchers(“/static/**”).permitAll()

    一起工作。您似乎忘记了添加类似的内容

        @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/")
            .setCachePeriod(31556926);
    }
    

    我假设您在/resources下的某处创建了/assets/imgs文件夹,是的。在“资源/统计”下有帮助吗?谢谢。不,还是不工作。我已经向githubso添加了代码,所以1点是您的spring版本/配置的重定向/路径映射逻辑。默认情况下(当前spring),url模式
    /static/*、/public/*、/resources/*
    /META-INF/*
    都映射到“web应用程序的类路径(根)”。默认情况下(当前maven/gradle)
    src/main/resources
    被复制到
    /target/classes/
    (这是应用程序的/一个类路径根)。。。第二点/不同点是您的安全配置…(但它应该与您的链接/用例//文件/类路径对齐)嗨。测试了3个选项spring.resources.static locations=classpath:/static/spring.resources.static locations=classpath:/static/assets-spring.resources.static locations=classpath:/static/assets/imgs/链接/cites/docs和结论参考当前(2.2.6.版本)的spring引导版本,请根据您的版本进行修订。
    spring.webflux.static-path-pattern
    /**
    Path pattern used for static resources.
    
        @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/")
            .setCachePeriod(31556926);
    }