The Mentawai controller supports search-friendly URLs out of the box. So instead of:
http://www.mysite.com/Topic.show.mtw?id=123
You can have:
http://www.mysite.com/mtw/Topic-show/123/how-to-make-search-friendly-urls-with-mentawai
Map the URLs inside the web.xml:
<!-- You must map all URLs starting with /mtw to the Mentawai controller --> <servlet-mapping> <servlet-name>Controller</servlet-name> <url-pattern>*.mtw</url-pattern> <url-pattern>/mtw/*</url-pattern> </servlet-mapping>
Give names to the parameters:
A pretty URL does not contain parameter names. The Mentawai controller takes them in order and place them in the action input with indexes starting at one. So for the URL:
http://www.mysite.com/mtw/Topic-show/123/how-to-make-search-friendly-urls-with-mentawai
The action input would have two vaules:
String id = input.getString("1"); // ===> "123" String title = input.getString("2"); // ===> "how-to-make-search-friendly-urls-with-mentawai"
You can work with the indexes but it is not very convenient. Therefore Mentawai allows you to assign names to the parameters in the application manager:
ActionConfig mainAction = action("/Page", PageAction.class) .prettyURLParams("id", "title") .on(SHOW, redir()) // for the pretty url .on(SUCCESS, fwd("/show_page.jsp"));
So now you can do:
String id = input.getString("id"); // ===> "123" String title = input.getString("title"); // ===> "how-to-make-search-friendly-urls-with-mentawai"
Redirecting to the pretty URL:
In you action, you want to enforce the correct URL with the correct id and title, so if the user types:
http://www.mysite.com/mtw/Topic-show/123/are-you-crazy
the action will automatically redirect to the correct URL. You can do that with the following piece of code inside your action:
if (isPrettyURL()) { // is the URL a pretty URL or a regular one? // check if URL is complete with the correct title... String correctTitle = topic.getPrettyURLFormattedTitle(); String inputTitle = input.getString("title"); if (inputTitle == null || !inputTitle.equals(correctTitle)) { String prettyURL = getPrettyURL("Topic", "show", id, correctTitle); // => /mtw/Topic-show/id/correctTitle redir(prettyURL); // <=== dynamic redirect (SHOW goes to redir() in the app manager) return SHOW; } }
NOTE: The method getPrettyURL belongs to BaseAction, so it is given to you. Same thing for the isPrettyURL method.
Formatting text to be displayed in the prettty URL:
The method topic.getPrettyURLFormattedTitle() above returns the title of your topic formatted to be show in the pretty URL. To format any string so it can be correctly shown in a pretty URL, you can use the following utility method:
public void setTitle(String title) { this.title = title; this.prettyTitle = HttpUtils.getPrettyText(title); } public String getPrettyURLFormattedTitle() { return prettyTitle; }