Search code examples
javaspringtomcatwar

Tomcat war - serve css files?


I need to serve arbitrary files together with the war. Where do I put it in webapps/$project and configure in web.xml?

web.xml

<?xml version="1.0" encoding="UTF-8" ?>
<web-app
        version="4.0"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
        http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd
        "
>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        <async-supported>true</async-supported>
    </filter>

    <filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Spring MVC-->
    <servlet>
        <servlet-name>servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <!--End of Spring MVC-->

    <servlet-mapping>
        <servlet-name>servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>
</web-app>

Solution

  • To serve static content such as html, css, etc., put the files under any directory under your $tomcat_home/webapps/$project directory.

    $tomcat_home
      +--bin
      +--conf
      +--...
      +--webapps
         +--your-app (Ex: file-server)
           +-- your-static-content-directory (Ex: static)
              +--css
                 +--a.css
                 +--b.css
              +--html
                 +--index.html
                 +--contact.html
           +-- WEB-INF
    

    Assuming your Tomcat runs on locally on port 8080, you can access the file a.css at http://localhost:8080/file-server/static/css/a.css