我不是第一个遇到这个问题的人,但我在这个网站上找到的任何东西都没有帮助我。也许有人可以用我自己的例子来解释错误在哪里以及为什么样式和脚本没有加载到 HTML 中?当我第一次创建并链接文件时,脚本和样式在没有配置设置的情况下加载。然后突然他们停止了(如果我没记错的话,在提交到 GitHub 之后),即使我没有对这些文件进行任何更改。原因是什么以及如何解决?
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/styles/css/**")
.addResourceLocations("classpath:/static/css/");
}
}
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig {
private final JWTTokenConfig jwtTokenConfig;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().disable()
.authorizeRequests(authorize -> authorize
.antMatchers("/register","/host_page", "/login", "/music_files").permitAll()
.antMatchers("/static/**","/background.jpg").permitAll()
.antMatchers("/swagger-ui/**", "/swagger-resources/*", "/v3/api-docs/**", "/swagger-ui.html").permitAll()
.antMatchers("/personal_office/**").authenticated()
.antMatchers(HttpMethod.GET, "/main").permitAll()
.antMatchers("/free_subscription").hasAnyRole("FREE", "OPTIMAL", "MAXIMUM", "ADMIN")
.antMatchers("/optimal_subscription").hasAnyRole("MAXIMUM", "OPTIMAL", "ADMIN")
.antMatchers("/maximum_subscription").hasAnyRole("MAXIMUM", "ADMIN")
.antMatchers("/admin_office/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore((Filter) jwtTokenConfig, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Host Page</title>
<link rel="stylesheet" href="/styles/css/host_page.css" type="text/css" />
</head>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class PetMusicStorageApplication {
public static void main(String[] args) {
SpringApplication.run(PetMusicStorageApplication.class, args);
}
}
为什么即使没有配置设置,样式和脚本最初也会加载,然后链接就消失了?
原因是 Spring Security 依赖项(当它全部停止工作时添加的)默认情况下也会阻止对任何静态文件的未经授权的访问。
在您的
MvcConfic
类中只需重写以下方法即可允许访问静态文件:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/statics/**", "/styles/**");
}