How do I make servlet requests look like static content requests?
Author: Deron Eriksson
Description: This Java servlet tutorial describes mapping URLs ending with .html to a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1 || Tomcat 5.5.20

Page:    1 2 >

One great thing about JavaSW web application technology is that it's so flexible. In fact, in your web.xmlW file, it's possible to map file extensions (like .html) to a servletW. This tutorial will describe this technique and how you can use it to pass values to a servlet. The tomcat-demo project has a web.xml file and one servlet called TestServlet.

'tomcat-demo' project

In web.xml, the url-pattern '/normal' maps to TestServlet, so if you hit "http://localhost:8080/tomcat-demo/normal", you get directed to TestServlet. The web.xml file also contains a url-pattern '*.html' mapping to TestServlet, which means that any requests to your application where the URL ends in '.html' will get directed to TestServlet. Examples of this are "http://localhost:8080/tomcat-demo/abc.html" and "http://localhost:8080/tomcat-demo/ok/123.html".


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="tomcat-demo" version="2.4"

TestServlet displays the request URL. It tries reading in the 'my-param' parameter if it's being passed to the servlet using the standard GET method. If 'my-param' is present, it displays the parameter value. If the parameter isn't present, it looks to see if it can pull out a value from the request URL between the last underscore and a '.html' on the URL. If it can do this, it displays this value. It also contains three hyperlinks that all get directed to TestServlet.

package test;


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

public class TestServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("This is the Test Servlet<br/>");
		String requestUrl = request.getRequestURL().toString();
		out.println("<br/>Request URL: " + requestUrl);

		String val = request.getParameter("my-param");
		if (val == null) {
			if ((requestUrl.lastIndexOf("_") != -1) && (requestUrl.lastIndexOf(".html") != -1)) {
				val = requestUrl.substring(requestUrl.lastIndexOf("_") + 1, requestUrl.indexOf(".html"));
				out.println("<br/>Value: " + val);
		} else {
			out.println("<br/>Parameter Value: " + val);

		out.println("<br/><br/><a href=\"normal?my-param=blah1\">This hits TestServlet</a>");
		out.println("<br/><a href=\"dynamic_blah2.html\">This looks static but it hits TestServlet</a>");
		out.println("<br/><a href=\"dynamic_blah3.html\">This also looks static but it hits TestServlet</a>");

(Continued on page 2)

Page:    1 2 >