1

I am working on a springboot project that consumes a weather api and shows the data on the browser using react, Anyway, It seems that I am missing some configurations or I might need to move files around in my project, The error in the browser shows that the js/css files are not reachable :

GET http://localhost:8080/demo/resources/css/neo.css browser.min.js:4 GET http://localhost:8080/demo/resources/js/WeatherManager.js 404 () browser.min.js:4 Uncaught Error: Could not load http://localhost:8080/demo/resources/js/WeatherManager.js at XMLHttpRequest.xhr.onreadystatechange (browser.min.js:4)

* WebConfig *

@Configuration
@ComponentScan
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    return resolver;
}

/**
 * We need to define 3 things to implement  
 * 1- Define message resource
 * 2- Define Local resolver internationalization
 * 3- Override interceptor 
 */
@Bean
public MessageSource messageSource(){
    ResourceBundleMessageSource messageSource=new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    return messageSource;
}

@Bean
public LocaleResolver localeResolver(){
    SessionLocaleResolver resolver =new SessionLocaleResolver();
    resolver.setDefaultLocale(Locale.ENGLISH);
    return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
    //you can add more resources here 
    registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/");
    registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/");
}

@Override
public void addInterceptors(InterceptorRegistry registry)
{
    LocaleChangeInterceptor changeInterceptor=new LocaleChangeInterceptor();
    changeInterceptor.setParamName("language");
    registry.addInterceptor(changeInterceptor);
}


}

* WebAppInitializer *

public class WebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    WebApplicationContext context = getContext();
    servletContext.addListener(new ContextLoaderListener(context));
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("*.html");
    dispatcher.addMapping("*.pdf");
    //Enable JSON response 
    dispatcher.addMapping("*.json");
    dispatcher.addMapping("*.jsx");

}

private WebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context =new AnnotationConfigWebApplicationContext();
    context.register(WebConfig.class);
    return context;
}

* DemoApplication *

@SpringBootApplication
@EnableAutoConfiguration
@EnableAsync
public class DemoApplication extends AsyncConfigurerSupport {

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("WeatherService-");
    executor.initialize();
    return executor;
}
}

JS/CSS files live under /resources/css/ /resources/js/

JSP pages live under WEB-INF/jsp

** weather.jsp page **

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <link rel="stylesheet" type="text/css" href="resources/css/neo.css">
 
 <title>Weather </title>
</head>
 <body>
  <div id="main" class="container">
   
  </div>
  <script type="text/babel" src="resources/js/WeatherManager.js"></script> 
 </body>
</html>

I have the source code at
github : [https://github.com/saifmasadeh/WeatherBoard][1]

Arar
  • 1,926
  • 5
  • 29
  • 47

1 Answers1

1

You should add this to your question:

<script type="text/babel" src="resources/js/WeatherManager.js"></script> 
<link rel="stylesheet" type="text/css" href="resources/css/neo.css">

This is where the problem is. You're importing via the wrong URL.

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
    //you can add more resources here 
    registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/");
    registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/");
}

The above method says when a user tries to access a url with the path /js/** look in /resources/js/.

Basically, if the user were to request localhost/context-root/js/script.js Spring would view this as localhost/context-root/resources/js/script.js

(That is not literally the case, but it explains the idea well enough.)

So when you try to import your script file resources/js/WeatherManager.js the resource handler doesn't know where to look. It doesn't know about anything with the path resources/**

What you want to do is import this way:

    <script type="text/babel" src="/js/WeatherManager.js"></script> 

This maps to the resource handler's "/js/** and looks up WeatherManager.js in /resources/js/. You need to do the same thing with your CSS file.

For another example of how this works, view my answer here.

(Also, you may need to use classpath:/resources/(js|css) as your resource location if this doesn't work.)

Community
  • 1
  • 1
Christopher Schneider
  • 3,745
  • 2
  • 24
  • 38
  • Your suggestion helped me to solve the issue but I had to update the script import part to be : ** ** , I wonder if that is related to fact that I updated the contextPath in application.properties file to ** server.contextPath=/demo ** – Arar Apr 17 '17 at 21:00
  • Ah... paths to static content files are sometimes trial and error. `/js/script.js` is probably looking at `localhost/js/script.js`. You may be able to use `js/script.js` without the preceeding forward slash depending on the path of the page. Alternately, I use a custom JSP tag to resolve script paths to avoid this problem. – Christopher Schneider Apr 18 '17 at 12:13