1

I am running a Spring MVC application and below is my Project Structure.

enter image description here

In my homepage.jsp , I have tried to load the js in the header section.

<head>
<script type="text/javascript" src="/resources/myScript.js"></script>
</head>

But I am getting the below error in the browser.

Failed to load resource: the server responded with a status of 404?

In my spring file, I have added

<resources mapping="/resources/**" location="/resources/" />

Can somebody point me to the error I am making?

PacMan
  • 1,358
  • 2
  • 12
  • 25
Nicky
  • 1,025
  • 3
  • 15
  • 29
  • can you show your servletcontext.xml !! – PacMan Jun 29 '16 at 16:51
  • What is your URL for accessing the `homepage.jsp` in your browser? If something like `http://localhost:8080/myapp/homepage.jsp`, then `myapp` is the "context path" of your application, and all absolute paths have to list that, e.g. `src="/resources/myScript.js"` should be `src="/myapp/resources/myScript.js"` when seen by the browser. Do not hardcode that value in your .jsp files, because it can change. There are many good articles about this if you search for them. – Andreas Jun 29 '16 at 17:00
  • Thanks @Andreas for the help. It helps me resolve the problem. – Nicky Jun 30 '16 at 15:24
  • Use like this core jstl library " /> – vikiiii Apr 09 '19 at 17:48

2 Answers2

1

Better to use Core JSTL to provide resource path in JSP and also define mvc resources in XML so that any mvc interceptor won't be applicable to resources' request.

<!-- UI resources exclusions from servlet mapping -->
<mvc:resources location="/resources/" mapping="/resources/**"/>

and use core jstl to load resource file.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<script src="<c:url value='/resources/myScript.js'/>"></script>
</head>
Mihir Gohel
  • 316
  • 2
  • 6
0

Find the actual path of the JS file in your WAR file. Check if you can access the JS file directly by calling its URL. For example - http://localhost:8080/YOURWARNAME/resources/myScript.js. Then include the script file in JSP with the EL ${pageContext.request.contextPath}. Like this

<script src="${pageContext.request.contextPath}/resources/myScript.js"></script>

More details in a similar issue - Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Community
  • 1
  • 1
Shankar
  • 2,625
  • 3
  • 25
  • 49