S
S
s2018-10-17 14:07:41
Java
s, 2018-10-17 14:07:41

Why js and styles are not connected to the html page in the Spring MVC project?

Why are styles and js not connected to the page? When displaying the page, these files get

failed to load resource: the server responded with a status of 404

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/sources/css/styles.css">

</head>
<body >
<h1>Hey there</h1>
<a href="/departments">click here</a>

<script src="/sources/scripts/initial_service.js"></script>
</body>
</html>

project structure: 5bc7179b6d956210804750.png
Web Config:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"controller"})
public class WebConfig  extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setViewClass(JstlView.class);
        bean.setPrefix("/WEB-INF/");
        bean.setSuffix(".html");
        return bean;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/sources/css/");
        registry.addResourceHandler("/image/**").addResourceLocations("/sources/image/");
        registry.addResourceHandler("/scripts/**").addResourceLocations("/sources/scripts/");
        registry.addResourceHandler("/*.html").addResourceLocations("/WEB-INF/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/main.html");
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
s, 2018-10-17
@solovladys

to work in the config it was necessary to set:

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/sources/**").addResourceLocations("/sources/");
        registry.addResourceHandler("/*.html").addResourceLocations("/WEB-INF/");
    }

or on html pages do not use part/sources/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question