0

I had a java script in my JSP, which worked fine. Now I want to move it to it's own file (abc.js). I created js-Folder and placed it there. I tried to include it with <script language="JavaScript" type="text/javascript" src="./js/abc.js"></script> which links to http://localhost:8080/ProjectName/js/abc.js (from link in HTML-Code of the page). I think this should be correct, isn't it?

Nevertheless I get errors in the browser console (Failed to load resource: the server responded with a status of 404 () abc.js)

Do I have to register the .js somewhere to be recognized?

Edit: My project structure is like this:

ProjectName
   |---WEB-INF
          |---page.jsp (that wants to include abc.js)
          |---js
               |---abc.js
Kinaeh
  • 277
  • 6
  • 16
  • what's the path of the page you're including the script file in? – H77 Feb 07 '18 at 07:31
  • @H77 it's direct in the /WEB-INF/-Folder of my project – Kinaeh Feb 07 '18 at 07:33
  • If you enter http://localhost:8080/ProjectName/js/abc.js in your browser, you can see the file? – Kloker Feb 07 '18 at 08:11
  • @Kloker no I also get 404 not found. But what would be the right path if that's the wrong? I speculated on '...or is not willing to disclose that one exists'. I already tried src="/WEB_INF/js/abc.js" or src="abc.js" (while placing it direct in WEB-INF-folder) but got the same result. – Kinaeh Feb 07 '18 at 08:17
  • 1
    Have you tried this one: https://stackoverflow.com/questions/22107788/how-include-an-external-js-file-in-a-jsp-page – Kloker Feb 07 '18 at 08:22
  • @Kloker thank you so much, this finally seems to work. thanks thanks thanks. – Kinaeh Feb 07 '18 at 08:28
  • @Kloker for this solution I had to place js folder the same level as WEB-INF. I was just wondering, placing it in WEB-INF and modifying src to src="${pageContext.request.contextPath}/WEB-INF/js/abc.js" would work as well but it doesn't. Could you tell me why? – Kinaeh Feb 07 '18 at 08:33

1 Answers1

2

The WEB-INF directory is not publicly accessible. Your HTML file accesses the JS file over an public URL. Details see here: Include javascript file from inside WEB-INF

So the solution for your problem is to place the JS file on the same level as the WEB-INF directory, so that it is served publicly and adjust the src link accordingly:

<script type="text/javascript" src="${pageContext.request.contextPath}/js/abc.js"></script>

(How include an external JS file in a JSP page)

Kloker
  • 499
  • 4
  • 14
  • thanks again, this also worked for my css files, so I finally god rid of these ugly <%@include file="/WEB-INF/css/style.css"%>-Tags. – Kinaeh Feb 07 '18 at 08:49