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
->
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.setName("search");
actionMapping.setMethod("getResults");
request.setAttribute(SEARCH_KEY, searchParameters);
-XP
