Quantcast
Viewing all articles
Browse latest Browse all 2

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.

Image may be NSFW.
Clik here to view.
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.


Viewing all articles
Browse latest Browse all 2

Trending Articles