Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way to include javascript in java servlets

i actually read a tutorial about servlets and i saw two different ways to include javascript in servlets.

  out.println("<html><head>");

  RequestDispatcher dispatcher = request.getRequestDispatcher(
      "/WEB-INF/javascript/functions.js");

  dispatcher.include(request, response);

  out.println("<title>Client Forms</title></head><body>");

and the other possiblity:

out.println("<html><head>");
out.println("<script language="text/javascript" src="functions.js">");
...

what is the difference between using an dispatcher or including directly? what is the better solution?

thx for your advices..

like image 401
J-H Avatar asked Oct 29 '12 15:10

J-H


2 Answers

<script language="text/javascript" src="functions.js">

In this case browser could cache script and it won't load on next page load if it's content haven't changed. Caching resources saves time on page load and network traffic. It doesn't matter whether you use this snippet in servlet or jsp.

By the way, there is a bug in your first way of including script. *.js files usually contain only javascript code, whithout markup, so you should add opening script tag before and closing script tag after including content of functions.js:

out.println("<script type='text/javascript'>");
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/javascript/functions.js");
out.println("</script>");
like image 82
artplastika Avatar answered Sep 26 '22 13:09

artplastika


When we use the RequestDispatcher, we are actually making request from the server for the said JS file and then we embed it into the response document.

On the other hand, embedding a tag will point the browser to make such a request to the server. I guess both the approaches are going to fetch the same results 99% of time at least if your file is on different server.

On the other hand, if it is on the same server, I think RequestDispatcher will be faster.

Server side caching will help in first approach and client side one in other.

like image 26
mihsathe Avatar answered Sep 24 '22 13:09

mihsathe