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

2020-03-03 07:56发布

问题:

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?

回答1:

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.



回答2:

I advise placing those js files under webapp folder. (I usually put them under webapp/resources/js)

And to make this path accessible, I use the mvc:resources tag:

This tag allows static resource requests following a particular URL pattern to be served by a ResourceHttpRequestHandler from any of a list of Resource locations. This provides a convenient way to serve static resources from locations other than the web application root, including locations on the classpath. The cache-period property may be used to set far future expiration headers (1 year is the recommendation of optimization tools such as Page Speed and YSlow) so that they will be more efficiently utilized by the client. The handler also properly evaluates the Last-Modified header (if present) so that a 304 status code will be returned as appropriate, avoiding unnecessary overhead for resources that are already cached by the client. For example, to serve resource requests with a URL pattern of /resources/** from a public-resources directory within the web application root, the tag would be used as follows:

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

Source: Spring Reference