Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
Hagai Cibulski Avatar asked Oct 29 '11 21:10

Hagai Cibulski


People also ask

Where does Spring MVC put CSS files?

Put your css/js files in folder src/main/webapp/resources . Don't put them in WEB-INF or src/main/resources .

Can we use CSS in JSP?

Well yes definitely you can. Consider JSP page as advanced HTML along with features of java. So surely you can use CSS in three ways: Inline CSS <h1 style="color:blue;"><%= someVariable %></h1>


1 Answers

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.

like image 91
digitaljoel Avatar answered Sep 21 '22 01:09

digitaljoel