Question

I have a struts2 application with a single page that may show one of a number of values stored in a database. The application is for a school with many departments and each department has many programs. The department page is accessed using a url like this

department.action?id=2

and the DepartmentAction will load the Department with id = 2 for display. All this is fine if the user is just browsing around the site but it gets uncomfortable if I want to provide a link to say the Engineering department in the newspapers. The link will have to be www.myschooldomain.com/department.action?id=2. I see a number of problems with this.

First, it is not user friendly. Second, it is prone to be broken because the departments are dynamically maintained and the id for a department could change without warning making the link unstable.

I would prefer to print a url like this: www.myschooldomain.com/department/engineering and have that somehow go to department.action?id=2.

My thoughts so far: create an action that will parse the url for the department name at the end then look it up by name. Maybe I could add a friendlyurl field to the database for each department.

But the question is: Is there a better way to do this in struts2?

Thanks.

Update (May 2009): I just happened to stumble back over this question and thought that I would say what I did to solve it.

I created a new package in the struts.xml called departments. In this package there is only one action mapped to *. So it catches all requests to mydomain.com/departments/anything.html.

In the action class I simply parse the url and look for the part between departments/ and .html and that is the name of the department so I can do a lookup in the database for it. This has been working fine for almost 5 months now and I have implemented it for other areas of the site.

Was it helpful?

Solution

This is normally done by mapping a servlet to, in your case '/department', and then using the path information (e.g., '/engineering') within the servlet to determine the ID.

Since the Struts2 dispatcher doesn't implement this behavior, it might be simplest to write your own servlet. This servlet would be configured with a map of valid "friendly" names to the unfriendly numeric identifiers. This could be an actual Map or it could be done with a database finder method.

The result of getPathInfo() would be used to look up the ID, and the request would be forwarded to the department.action. Handle the null case too, which means the user is trying to browse the /departments/ directory.

OTHER TIPS

You could use the URL Rewrite filter

This avoids the need for any additional servlet or Java code but requires XML descriptors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top