The Servlet within – Servlet creates Javascript coding

The following explains how to create Javascript output with a servlet and how to include this Javascript into a static HTML page. The generated Javascript code will again write some text into the HTML pages.

For this tutorial you need to use Eclipse and know how to develop servlets with Eclipse.

See Servlet and JSP development with Eclipse
in case you need an introduction.

Create a new dynamic Web project “de.vogella.wtp.javascript”. Create a package “de.vogella.wtp.javascript”.

Create a new servlet “JavaScriptServlet” in your package. The URL mapping should be done to /JSCounter.js.

jscounter10


package de.vogella.wtp.javascript;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class JavaScriptServlet
 */
public class JavaScriptServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private AtomicLong counter = new AtomicLong(0);   // We start with zero

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		// Set the session valid for 2 secs
		session.setMaxInactiveInterval(1);
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		
		if (session.isNew()) {
			counter.incrementAndGet();
		}
		String s = "br.writeln(\"This site has been accessed "+ "" + counter.get() +"
"+"\");"; out.println("var br=document;"); out.println(s); } }

Run the servlet, as a result the system should give you a popup with a file to save.

Create now a static HTML page “index.html” under WebContent which calls the servlet. Example can be download from here.

Right click to download this file

This HTML page will call the servlet. The HTML page will then receive the response of the servlet and interprets the response as JavaScript. Open this HTML page in a browser while your servlet is running to display the counter.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Servlet. Bookmark the permalink.