Serve static content in Java web application example

In this section I will teach you how you can configure your web.xml to server static content from Java web application.

Serve static content in Java web application example

Static content - Serve static content in Java web application example

Java web application is very flexible and it allows the developers to build complex applications for the companies. In this section I will show you how you can use the default servlet of Java web application to serve the static content very convinently. If you have static content such as images, .js files, .css files or any other static content then you use the Java web applications default servlet to server these contents.

Serve static content

This tutorial teaches you how to use the default server of Java web application and serve the static content. You to add the appropriate url mapping in the web.xml file of the web application and restart the server to serve static content deployed with the web application.

What is default server?

The default server is initialized the servlet container to serve the web request. This servlet can be configured to server the static content of you web application.

How to configure web.xml file to server static content?

Suppose you have images, css, js and static directory in your web application where you have added static content and you want to serve these files. In this case you can use default server and serve static content. After all the dynamic contents other then in these url can be served by other servlets.

Here is the configuration that you should add in the web.xml file of your web application:

web.xml

<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>/static/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>/css/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>/js/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>/images/*</url-pattern>
</servlet-mapping>


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

After add these code into your web.xml file, restart the server. After restart of the tomcat server everything will start working as expected.

In the above example we have defined SpringMVCServlet in the web.xml and this servlet will serve other urls dynamically. The SpringMVCServlet  is not defined as default servlet.

We have used the default servlet inherited from the servlet container. This configuration should work with all the servlet containers. We have tested this on the Jetty and Tomcat servers.

Related Tutorials: