Learn the meaning of "server side" and "client side".
Go get yourself a decent JSP/Servlet book. This all is fairly trivial.
JavaScript is generated on the server, then you are correct.
Relying on this still causes a connection leak because it doesn't happen right away