STS Spring MVC: How to include a JS file in a JSP

Hagai Cibulski picture Hagai Cibulski · Oct 29, 2011 · Viewed 14k times · Source

I installed SpringSource Tool Suite 2.8.0. I'm trying to include a JS file in a JSP, using the Spring MVC template as a starting point. My JSP looks like this:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>Home</title>
    <script type="text/javascript" src="/a.js"></script>
</head>
<body>
    Hello world!  
</body>
</html>

a.js is under src\main\resources and looks like this:

window.alert("A");

The result is that "Hello world!" gets printed without the alert :-(

I tried putting the JS file in different places, changing the src to be with/without "/", and even adding a servlet-mapping in web.xml to use "default" servlet for "*.js". Nothing seems to work.

What am I doing wrong?

Answer

digitaljoel picture digitaljoel · Oct 30, 2011

is the js file getting included in your .war file? I usually put my js and css in src/main/webapp. something like src/main/webapp/js and src/main/webapp/css.

Secondly, you can reference it appropriately using c:url which will take care of putting the app context on there and stuff.

<script type="text/javascript" src="<c:url value="/a.js" />" />

You can use firebug or chrome's developer tools to see if you are getting a 404 for a.js and see what path it is actually requesting.