How to include JavaScript library into Spring MVC

2020-06-24 17:15发布

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.

3条回答
你好瞎i
2楼-- · 2020-06-24 17:38

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.

查看更多
Emotional °昔
3楼-- · 2020-06-24 17:42

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.

查看更多
在下西门庆
4楼-- · 2020-06-24 17:44
  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>
    
查看更多
登录 后发表回答