Friday, August 17, 2007

Struts2 + Custom URLs

For the web application that I was building using Struts, I needed custom ( read: cool ) URLs.

Traditionally, struts URL would be of the format
where do is the action extension.

But rather, I wanted a clean URL like

To achieve this, I had to do the following

-> In my custom struts.xml, I added a line which overrides the default ActionMapper class

Write the custom class which should extend ActionMapper

With a custom Mapper Class, the scope of formats of URL is limited only by imagination :P
To take up an example, lets say we want to have a "clean" search URL
To achieve the above, we need the following
  • Action class called Search and corresponding function called getResults(). This class also needs to implement ServletRequestAware to get hold of the ServletRequest ( which would contain the search parameters )
  • In the custom Action Mapper Class, we would need to use regex ( split on "/" ) to understand the URL and if we find the first token is "search", we could set
request.setAttribute(SEARCH_KEY, searchParameters);



Johan said...

My understanding is that you don't need to set the search parameters on the HttpRequest as they can be set on the ActionMapping class. Then your action class would not have to implement SessionAware.

For what it is worth...

Rakesh Rajan said...


Setting the parameter directly on the action class may not be a clean solution since I might have various cases where I want to pass something along the URL

Since we do have couple of cases like this, it made sense to make it generic.