Не умеет делиться статическими ресурсами - PullRequest
0 голосов
/ 08 февраля 2019

Я изучаю весну в руководствах YouTube) Resenty Я попытался начать свой собственный проект и получил некоторые проблемы.Ресурсы из каталога / static / ** не предоставлены внешнему миру - ошибка 404./ Static / находится в / src / main / resources /

Я пытался: добавить

spring.resources.static-locations=/js/,/css/
spring.mvc.view.prefix=/static/css/
spring.mvc.view.suffix=.css

в application.properties - без изменений.

Когда я добавлю

registry.addResourceHandler("/img/**").addResourceLocations("file:///"+uploadPath+"/");

до public void addResourceHandlers(ResourceHandlerRegistry registry)

  • файлы с пути загрузки прекрасно распределяются.

Если я добавлю файл .js в / static / или / static /js IDEA обычно связывает вызовы из моего кода со скриптами.Но сценарии не работают при запуске приложения.

@Configuration

public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/login").setViewName("login");

    }

    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/static/**")

                .addResourceLocations("classpath:/static/");
    }}


    WebSecurityConfig

    @Configuration

    @EnableWebSecurity

    @EnableGlobalMethodSecurity(prePostEnabled = true)

    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override

    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()

                .antMatchers("/users","/static/**").permitAll()

                //.anyRequest().authenticated()

                .anyRequest().permitAll()

                    .and()

                .formLogin()

                .loginPage("/login")

                .permitAll()

                    .and()

                .rememberMe()

                    .and()

                .logout()

                .permitAll();
    }

    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws 
    Exception {

        auth.userDetailsService(userService)

                .passwordEncoder(passwordEncoder);
    }
} 

application.properties

spring.datasource.driver-class-name=org.postgresql.Driver

    spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

    spring.datasource.url=jdbc:postgresql://localhost:5432/banking

    spring.session.store-type=jdbc

    spring.session.jdbc.initialize-schema=always

    spring.datasource.username=postgres

    spring.datasource.password=123456

    spring.jpa.hibernate.ddl-auto=update

    spring.jpa.generate-ddl=false

    spring.jpa.show-sql=true

    spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

    spring.freemarker.expose-request-attributes=true

структура проекта

├───main
│   ├───java
│   │   └───web
│   │       ├───configs
│   │       ├───controllers
│   │       ├───domain
│   │       ├───Repositories
│   │       ├───service
│   │       └───validator
│   └───resources
│       └───templates
│           ├───parts
│           └───static
│               ├───css
│               └───js
└───test
    └───java

1 Ответ

0 голосов
/ 08 февраля 2019

Пожалуйста, просто переместите свои каталоги с

 src/main/resources/templates/static/

на

 src/main/resources/static/

По умолчанию Spring Boot будет обслуживать статический контент из папки / static (или / public или / resources или/ META-INF / resources) в пути к классам или из корня ServletContext

Спасибо

...