'CSS and JS file not loading while deploying war file on apache tomcat

was using the spring-boot-starter-web-mvc for initial development.When I deploy the war file on the server it is not loading css and js files, but when I run the same code using spring boot, it is working fine. Below is the directory structure and configuration loading the js and css file. Can anyone please let me know how to what is the problem ? Using only java based configuration for project. I have referred 8.1.1 in the doc before deploying the project and used the same pom file configuration as below.

Directory structure

Configuration file -

public class ViewWebAppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // configuration for assets/ static files
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
        rb.setBasenames(new String[] { "validation" });
        return rb;
    }

}

pom.xml file

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <log4j.version>2.7</log4j.version>
    </properties>

    <dependencies>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
        </dependency>
         <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Dependency for rendering jsp pages  -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>tomcat</groupId>
            <artifactId>jasper-compiler</artifactId>
            <version>5.5.23</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>tomcat</groupId>
            <artifactId>jasper-runtime</artifactId>
            <version>5.5.23</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>tomcat</groupId>
            <artifactId>jasper-compiler-jdt</artifactId>
            <version>5.5.23</version>
            <scope>provided</scope>
        </dependency>
        <!-- Dependency for rendering jsp pages  -->

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
    </dependencies>

Loading the js and css using spring-tags as below -

<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<spring:url value="/resources/assets/js/custom.min.js" var="customJS" />
<script src="${customJS}"></script>

<link href="${customFieldAgent}" rel="stylesheet"/>
<spring:url value="/resources/assets/css/customfieldAgent.css" var="customFieldAgent" />

Below is the server log -

17:03:10.014 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Did not find handler method for [/${starrrJS}] 17:03:10.014 [http-nio-8080-exec-7] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/ui/$%7BstarrrJS%7D] in DispatcherServlet with name 'dispatcher' 17:03:10.014 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request 17:03:10.018 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/ui/$%7BcustomJS%7D] 17:03:10.018 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /${customJS} 17:03:10.019 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Did not find handler method for [/${customJS}] 17:03:10.019 [http-nio-8080-exec-4] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/ui/$%7BcustomJS%7D] in DispatcherServlet with name 'dispatcher' 17:03:10.019 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request



Solution 1:[1]

Try this way it is working for me.

Project Structure:

src/main/webapp/static/[css,js,images]
src/main/webapp/WEB-INF/views/[for all .jsp pages]

Configuration

@Configuration
@ComponentScan(basePackages = "parent package name where all packages reside")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // when static resources are inside resources folder under WEB-INF
        // registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");

        // when static resources are inside static folder under webapp
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }
}

Let DispatcherServlet know how to pack things up...

import javax.servlet.Filter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { ApplicationConfiguration.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }     
}

Now call these on view like...

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link href="<c:url value='/static/css/application.css' />" rel="stylesheet"></link>
    </head>

Add this in your pom.xml

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

Hope this will help you.

Solution 2:[2]

In my Spring Boot project,i tried to deploy as WAR file into TOMCAT,but it does not recognize the resource path,it throws 404 File not found error,But when i run as SpringBootApplication,it works properly,issue only when deploy as a WAR file into TOMCAT. so finally i revealed the issue now it works perfectly on my project structure enter image description here

adding those lines into application.properties file

spring.resources.add-mappings=true
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/

i got from https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

it works perfectly...

Solution 3:[3]

for this js,images,css or from outside of the war file images or any file can be shown and also get access by using this below line is common to two scenarios

spring.resources.add-mappings=true

For in the spring boot war file or any file of spring to get accessed or shown this u have to put in application.properties file or any property file

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/

For external access file or showing external files of images u may put as

spring.resources.static-locations=file:///C:/xxxxxxxxx/xxxxxxxxx

AS said vignesh R it was working great try it

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mfaisalhyder
Solution 2
Solution 3 Pradeep