【问题标题】:can't serve static files spring弹簧不能提供静态文件
【发布时间】:2022-08-17 11:18:49
【问题描述】:

我对 spring 真的很陌生,这就是为什么它可能是一个非常愚蠢的问题,但我在提供静态文件时遇到了麻烦。我正在为图书馆应用程序创建一个 REST api,并且当用户尝试添加一本书时有一些逻辑:

  1. 我从 SecurityContextHolder 获得主要用户。
  2. 我添加书籍并将书籍添加到用户的书籍列表中
  3. 我从 base64 编码字符串中读取字节并将其写入 pdf 文件,存储在 /resources/static

    那行得通。但我不知道如何获取此文件。我试着下一步做:

    1. 我创建了扩展WebMvcConfigurerResourceConfig 类,但它不起作用:
      @Configuration
      public class ResourceConfig implements WebMvcConfigurer {
      
          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
              registry
              .addResourceHandler(\"/static/**\")
              .addResourceLocations(StaticAbsolutePath.getPath());
          }
      }
      
      1. 哦,StaticAbsolutePath.getPath() 是我用来获取静态目录路径的方法:
      public class StaticAbsolutePath {
          private static final String path = \"A:\\\\java\\\\projects\\\\books\\\\src\\\\main\\\\resources\\\\static\";
      
          public StaticAbsolutePath() {
          }
          public static String getPath() {
              return path;
          }
      }
      
      1. 我决定我的安全配置阻止了这条路径,因为我没有被授权,所以我将它添加到配置类:
      http.authorizeRequests().antMatchers(\"/static/**\").permitAll();
      

      但它也没有用。当我尝试向http://localhost:8080/static/1252356147.pdf 服务时,它会显示“Whitelabel Error Page”。

      这是资源目录的屏幕:

      因此,如果您知道可能是什么问题,请告诉我,我真的很感激!

      以下是 SecurityConfig 的完整代码:

      @Configuration @EnableWebSecurity
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
          @Autowired
          private UserDetailsService userDetailsService;
          private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
      
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
          }
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManagerBean());
              customAuthenticationFilter.setFilterProcessesUrl(\"/api/login\");
              http.csrf().disable();
              http.authorizeRequests().antMatchers(\"/api/login/**\").permitAll();
              http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
              http.authorizeRequests().antMatchers(HttpMethod.POST, \"/api/users/\").authenticated();
              http.authorizeRequests().antMatchers(HttpMethod.GET, \"/api/user/current\").authenticated();
              http.authorizeRequests().antMatchers(HttpMethod.POST, \"/api/books/**\").authenticated();
              http.authorizeRequests().antMatchers(HttpMethod.GET, \"/api/books/**\").permitAll();
              http.authorizeRequests().antMatchers(HttpMethod.PUT, \"/api/books/**\").authenticated();
              http.authorizeRequests().antMatchers(\"/static/**\").permitAll();
              http.addFilter(customAuthenticationFilter);
              http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
          }
      
          @Bean
          @Override
          public AuthenticationManager authenticationManagerBean() throws Exception {
              return super.authenticationManagerBean();
          }
      }
      

    标签: java spring spring-boot static


    【解决方案1】:

    首先,静态文件是指很少更改的文件,例如 HTML、CSS 文件等。在您的情况下,用户可以随时上传 pdf 文件,表明它不是静态文件。我的建议是使用不同的目录来存储 PDF 并在您的 resourceConfig 中提供该路径。但是,如果您想将其存储在 /resources/static 目录中,则可以执行类似的操作。

    资源配置:

    @Configuration
    @EnableWebMvc
    public class ResourceConfigs implements WebMvcConfigurer {
    
    
    
        private static final String[] CLASS_PATH_RESOURCE_LOCATIONS = {
                "file:///home/akhil/Downloads/Test_Project/src/main/resources/static/"
        };
    
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**")
                    .addResourceLocations(CLASS_PATH_RESOURCE_LOCATIONS)
                    .setCacheControl(CacheControl.noCache().cachePrivate())
                    .resourceChain(true)
                    .addResolver(new PathResourceResolver());
        }
    
    }
    

    使用此配置,您可以拥有这样的链接, http://localhost:8080/static/**

    您不需要为此配置弹簧安全性

    【讨论】:

      猜你喜欢
      • 2020-11-13
      • 2012-06-15
      • 2018-02-06
      • 2018-10-23
      • 2021-07-08
      • 2013-06-02
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多