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
http://www.myapp.com/login.do
where do is the action extension.

But rather, I wanted a clean URL like http://www.myapp.com/login

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
http://www.myapp.com/search/abc+xyz
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
actionMapping.setNamespace(namespace);
actionMapping.setName("search");
actionMapping.setMethod("getResults");
request.setAttribute(SEARCH_KEY, searchParameters);


-XP

2 comments:

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...

Johan,

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
E.g
http://www.myapp.com/search/abc+xyz
http://www.myapp.com/update/abc+xyz
etc

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

Cheers!