JavaScript with Spring MVC doesn't work

孤街浪徒 提交于 2019-12-01 00:45:07
<script type="text/javascript" src="${pageContext.request.contextPath}/js/niceforms.js"></script>
<link href="${pageContext.request.contextPath}/css/niceforms-default.css" rel="stylesheet" />

Use the above code.. You need to specify it dynamically, not statically..

Use absolute path in your jsps for javascript and css

add this in your jsp

<%
    String path = request.getContextPath();
%>

Change these two lines

<script language="javascript" type="text/javascript" src="<%=path%>/js/niceforms.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="<%=path%>/css/niceforms-default.css" />

There are two things i am seeing here

  1. The default servlet is not having any servlet mapping. The tomcat documentation says like this http://tomcat.apache.org/tomcat-5.5-doc/default-servlet.html (i believe you are using tomcat).
  2. If there is path problem in jsp try using the jstl core librarie's <c:url/> which is more cleaner. http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/c/tld-summary.html

Instead of that ugly ${pageContext.request.contextPath}, if you use this in your template:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

Then you can do this:

<spring:url value="/resources/jquery-2.1.4.js" var="jqueryJS" />
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "${jqueryJS}";
    document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!