Posts Tagged ‘servlets


Extracting and Tokenizing HTTP Path Variables

This page describes how to extract and tokenizing HTTP path variable(s).


URL Path is often used by RESTful applications to pass scoping information. Applications often parse this information and use it to retrieve data from the server-side.

Modern frameworks like Spring MVC 3 and The RESTlet frameworks have means of extracting tokens from HTTP Path. However if you aren’t using those frameworks then the information on this page will be helpful.

The utility class described on this page will allow you to extract tokens present in URL paths. For example “item/{itemId}/subcomponent/{subComponentId}”


  • Maven 2
  • Spring 2.5.6 or above
  • Basic understanding of Struts MVC

Start a new project

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp

groupId: com.test
artifactId: pathVarTest

Answer the rest of the questions with defaults “Just hit the enter key”,

cd to the project base folder.

cd pathVarTest

Since this is a web project maven2 does not create the java source folder.

Create missing folders now.
mkdir -p src/main/java/com/test
mkdir -p src/main/webapp/WEB-INF/jsp

Modify the project Configuration

The pom.xml file should look something like this.

<project xmlns="" xmlns:xsi=""
  <name>pathVarTest Maven Webapp</name>


The following is where the URL path gets tokenized. It is a static utility class that could be used from a Spring MVC controller or a HTTPServlet Class.


package com.test;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

 * Helper class to allow URL path's to be parsed into 
 * EL Expression type tokens.
public class PathUtil {
	public static final Map<String, String> getPathVariables(String patternStr,
			String[] names, String path) {
		String regExPattern = patternStr.replace("*", "(.*)");
		Map<String, String> tokenMap = new HashMap<String, String>();
		Pattern p = Pattern.compile(regExPattern);
		Matcher matcher = p.matcher(path);

		if (matcher.find()) {
			// Get all groups for this match
			for (int i = 0; i <= matcher.groupCount(); i++) {
				String groupStr =;
				if (i != 0) {
					tokenMap.put(names[i - 1], groupStr);
		return tokenMap;

Spring MVC Controller

The following controller class responds to the following URL’s

  • item/{itemId}
  • item/{itemId}/subcomponent/{subComponentId}


package com.test;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
public class ItemController {
    @RequestMapping(value="/item/*", method = RequestMethod.GET)
    public String itemInfo(HttpServletRequest request) {
    	final String pattern = "/item/*";
		final String[] names = {"itemId"};
		Map<String, String> pathMap = PathUtil.getPathVariables(pattern, names, request
		request.setAttribute("pathMap", pathMap);
        return "index";
    @RequestMapping(value="/item/*/subcomponent/*", method = RequestMethod.GET)
    public String subComponentItemInfo(HttpServletRequest request) {
    	final String pattern = "/item/*/subcomponent/*";
		final String[] names = {"itemId", "subComponentId"};
		Map<String, String> pathMap = PathUtil.getPathVariables(pattern, names, request
		request.setAttribute("pathMap", pathMap);
        return "index";


The following JSP is used to display the Hash Map that contains the results. I haven’t put any work in making it look pretty. Its just functional.


<%@ taglib uri="" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="" lang="en" xml:lang="en">
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="en-us" />
<h3>This are the tokens from the URL Path Info String</h3>
<h3><c:out  value="${pathMap}"/></h3>

Web App Configuration


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
    xmlns="" xmlns:web=""
    id="WebApp_ID" version="2.5">
    <display-name>Archetype Created Web Application</display-name>

Spring MVC Configuration file

This is a pretty standard Spring MVC configuration file.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:context=""
    <context:annotation-config />
    <context:component-scan base-package="com.test" />
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <bean id="viewResolver"
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />

Test the application

Start the Jetty Servlet Engine to test the application with 1 scoping variable.

  1. Open a command line window and navigate to the project base directory.
  2. Type the following at the command line:
    mvn clean compile jetty:run
  3. Navigate to the following URL: http://localhost:8080/app/item/235
  4. You should see the next page which prints “{itemId=235}”.

Test the application with multiple scoping variables.

  1. Navigate to the following URL: http://localhost:8080/app/item/123/subcomponent/456
  2. You should see the next page which prints “{subComponentId=456, itemId=235}”.

Creating a WAR file

If you want to run the application in another environment you can create a war file and drop it into a server of your choice. This method will also package up any runtime dependencies and put them in the /WEB-INF/lib folder of the WAR file.

mvn clean compile package

The war file should appear in the project’s “target/” folder…

That’s all for now!


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

November 2017
« Oct    

Blog Stats

  • 842,358 hits