简体   繁体   中英

How to include JavaScript library into Spring MVC project (jQuery or Dojo, for instance)

I have read more than 5 related threads here, but could not the answer: step-by step instructions. Till now I have the STS Spring MVC template structure and try to put jquery.js somewhere in my project (unfortunately, nobody says, where it should be). So, please say:

  1. where to place jquery.js in the project structure?
  2. how to refer to this location from .jsp?
  3. any other actions needed? like maven, app config changes?

My jsp works perfectly with http://code.jquery.com/jquery-1.8.3.js , but refuses to work with local file /js/jquery-1.8.3.js . And a strange thing - when jsp can not find the script, app server complaints about it, but when it (have found?) the library, no warnings, but jquery also doesn't work.

The JavaScript files are just resources that must be downloaded by the browser. So you put them where you want under the webapp root directory.

Suppose you put your file under /js/jquery.js (in the WebContent directory of your web project). And suppose your webapp has /myFirstWebApp as context path. This means that the root of the webapp, once the application is deployed, will be at

http://localhost:8080/myFirstWebApp/

and that your JS file will thus be at

http://localhost:8080/myFirstWebApp/js/jquery.js

To generate a URL in a webapp, you typically use the <c:url> tag:

<script src="<c:url value='/js/jquery.js'/>></script>

The c:url tag takes care of the context path:it prepends it to the absolute URLs you give it in order to halp you change the context path later.

for includes, it's a better to write

<script type="text/javascript" src="<c:url value='/js/jquery-1.8.3.min.js'/>"></script>

The js folder should be placed under WebContent folder.

  1. Copy the JQuery library under WebContent (like, WebContent\\jquery\\js\\jquery-1.9.1.js is valid)

  2. In JSP:

      <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> ... <head> <spring:url value="/jquery/js/jquery-1.9.1.js" var="jqueryUrl" /> <script src="${jqueryUrl}"></script> <spring:url value="/jquery/js/jquery-ui-1.10.3.custom.js" var="jqueryJsUrl" /> <script src="${jqueryJsUrl}"></script> </head> 
  3. In spring-context.xml add:

      <mvc:resources location="/jquery/" mapping="/jquery/**" /></beans> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM