Spring MVC – How to include JS or CSS files in a JSP page

In this tutorial, we will show you how to include static resources like JavaScript or CSS in a JSP page.

Summary steps :

  1. Put static resources like cs, js or images into this folder webapp\resources
  2. Create a Spring mvc:resources mapping
  3. Include in JSP page via JSTL tag c:url or Spring tag spring:url

P.S This project is tested with Spring 4.1.6.RELEASE.

1. Project Directory

A standard Maven folder structure, puts the static resources like js and css files into the webapp\resources folder.

spring-mvc-include-css-

2. Spring Resource Mapping

Declares mvc:resources, to map “url path” to a physical file path location.

spring-web-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.mkyong.web" />

    <bean
	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix">
		<value>/WEB-INF/pages/</value>
	</property>
	<property name="suffix">
		<value>.jsp</value>
	</property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/theme1/"  
	cache-period="31556926"/>

    <mvc:annotation-driven />
	
</beans>

In the above example, any requests from this url pattern /resources/**, Spring will look for the resources from the /resources/mytheme1/ instead.

In future, you can easily change to a new theme by updating the mvc:resources


	<mvc:resources mapping="/resources/**" location="/resources/theme-new/" />

3. Include in JSP Page

To include CSS or JS in a JSP page, you can use JSTL tag c:url or Spring tag spring:url.

3.1 JSTL tag c:url example.

hello.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">
    <script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"></script>
    <script src="<c:url value="/resources/js/main.js" />"></script>
</head>
<body>
<h1>1. Test CSS</h1>

<h2>2. Test JS</h2>
<div id="msg"></div>

</body>
</html>

3.2 Spring tag spring:url example.

hello.jsp

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html>
<html lang="en">
<head>
	<spring:url value="/resources/css/main.css" var="mainCss" />
	<spring:url value="/resources/js/jquery.1.10.2.min.js" var="jqueryJs" />
	<spring:url value="/resources/js/main.js" var="mainJs" />
	
	<link href="${mainCss}" rel="stylesheet" />
    <script src="${jqueryJs}"></script>
    <script src="${mainJs}"></script>
</head>
<body>
<h1>1. Test CSS</h1>

<h2>2. Test JS</h2>
<div id="msg"></div>

</body>
</html>

3.3 Javascript file.

/webapp/resources/mytheme/js/main.js

jQuery(document).ready(function($) {

	$('#msg').html("This is updated by jQuery")

});

3.4 CSS file.

/webapp/resources/mytheme/css/main.css

h1{
	color:red;
}
Alternatively
For those who hates JSTL, you can use the “page context” variable to get the resources like this :


<link href="${pageContext.request.contextPath}/resources/css/main.css" rel="stylesheet" >

4. Demo

Run the project with Maven command : $ mvn jetty:run

URL : http://localhost:8080/spring-css/

spring-mvc-include-css-demo

5. Static resources in WEB-INF?

Q : Can I put the static resources in the WEB-INF folder?
A : Yes, you can, the Spring mapping will still work, For example,


	<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/theme1/" />

But, this is not a good practice. You can ignore the rule, but many developers and plugins will look for the static resources in the same level of WEB-INF, not inside the WEB-INF.

Download Source Code

Download it – spring-mvc-css-example.zip (57 KB)

Reference

  1. Spring MVC serving static resources

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
60 Comment threads
12 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
65 Comment authors
debotush DamNorbu SherpaShameerMd. Mahbub AlamEduardo Recent comment authors
newest oldest most voted
raj mohan
Guest
raj mohan

js is not applying in html only css is working

Mansoor
Guest
Mansoor

Thankyou sir , it is working,
but my doubt is, can i map resource from url(http:// or ftp://) instead from file://

Naveen
Guest
Naveen

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 31 in XML document from ServletContext resource [/WEB-INF/minku-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 31; columnNumber: 77; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘mvc:resources’.

mhmd
Guest
mhmd

Finally, it’s working !!! Thank you very much.
How about putting these js and css inside the WEB-INF ?

Tony
Guest
Tony

Well done

rankun203
Guest
rankun203

Thank you.

Guest
Guest
Guest

what is maven configuration to include these js and css inside the WEB-INF ?

Hello
Guest
Hello

This is child’s play. How about the path problem inside CSS and JS files?

Hello
Guest
Hello

If i want a relative path inside a JS file, I have to map my JS resource path in a controller. When it’s called, I fetch the actual file in Java, get the relative path from HttpServletRequest and output modified JS file. Isn’t there a better way? The same thing is with CSS files.

Rohit More
Guest
Rohit More

Thank you.
specially I like your this comment :
“For those who hates JSTL, you can use the “page context” variable to get the resources like this :” 🙂

Prashant Gupta
Guest
Prashant Gupta

Its is good way to customizing the CSS and JS file to the JSP

Joy
Guest
Joy

what about in a portal page with friendly URL

Jiménez Geovaninho
Guest
Jiménez Geovaninho

Thanks so much !!! ..

Greetings

Rafael
Guest
Rafael

Yeah! Science!!

Thank you man! You’re awesome!!!

Oreli
Guest
Oreli

Hello. This tutorial is great but I would like to mention that this didn’t work right off the bat (I was getting 404 on css and js resources). Cause of the error was double double quotes while including css and js files

<link href="” rel=”stylesheet”>. I simply put single quotes on c tag and it worked <link href="” rel=”stylesheet”>

Keren
Guest
Keren

Hi mkyong, I’m a newcomer to spring, mongoDB and JQuery. Your site has helped me so much! Thanks to you my project is up and running from scratch! Thank you!

macleo
Guest
macleo

mkyong ,thanks ,I love Malasiya

macleo
Guest
macleo

mkyong,How about putting these js and css inside the WEB-INF ?

stevematdavies
Guest
stevematdavies

Why should the front end resources be mapped to back end functionality??? Why not just put them in WEB-INF, keep the web and back end separated. Adding them as a servlet dependdency seems to coupled and akward.

Andry Rakotozafinirina
Guest
Andry Rakotozafinirina

this work fine on tomcat but when i use Glassfish it doesn’t work , any help?

rkstha
Guest
rkstha

Thanks for this article.

jb
Guest
jb

how add .ejs file?

vid
Guest
vid

When i do the resource mapping ( ), i am getting No mapping found for HTTP request with URI [/SpringMvc/home] in DispatcherServlet with name ‘mvc-dispatcher’. This is how my login controller looks.

@Controller
@RequestMapping(“/”)
public class LoginController {

@RequestMapping(method = RequestMethod.GET, value = “/home”)
public String showLogin(ModelMap model) {
return “logIn”;
}

@RequestMapping(method = RequestMethod.POST, value = “/resource”)
public String showResource(ModelMap model) {
return “resourceTracker”;
}

}

When i don’t do the resource mapping, its not able to find my css file with the below error

[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (main.css, line 0) http://localhost:8080/SpringMvc/resources/mytheme/css/main.css

Tahseen Haque
Guest
Tahseen Haque

Thank you so much for taking the time to write these instructions up

ashwini
Guest
ashwini

Thanks a lot
was struggling from an hour as my js and css files where not getting loaded

Hateless
Guest
Hateless

OOO I love you!!! 12 hours in a trash and finally solution.

Umesh
Guest
Umesh

Thanks Lot sir

Vaibhav Srivastav
Guest
Vaibhav Srivastav

Finally It’s Working.It was good for me.

Thanks

Shahriar Husainy
Guest
Shahriar Husainy

Great post! Thank you so much!

dude
Guest
dude

Thank you thank you thank you so much! Great tutorial!