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

六月ゝ 毕业季﹏ 提交于 2019-11-30 21:09:40

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!