SEO Friendly URL in Struts 2

A SEO friendly URL supplies request parameters as a part of the URI. Such as /edit-game/zombi-2014 rather than /edit-game?gameId=zombi-2014. This is because Google does not index any text that comes after “?”.

By default, Struts 2 has SEO friendly URL disabled. But, this can be enabled rather easily. In this tutorial, I will show you how to do that in an application using the convention plugin and annotation.

Enable Parameter in URI

Open your struts.xml and add these constants:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
 
<struts>
 <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
 <constant name="struts.enable.SlashesInActionNames" value="true"/>
 <constant name="struts.patternMatcher" value="namedVariable"/>
</struts>

Save changes.

Develop the Action Class

In your action class, define a property where the parameter will be saved. For example, gameId below.

public class GameAction {
 private String gameId;
 //getGameId, setGameId etc.
 //...
}

Next, for an action handler method, specify the property name in the action URI.

@Action("/edit-game/{gameId}")
public String editGame() {
 System.out.println("Game ID is: " + gameId);
 
 return "form";
}

That’s it. Now, you can use the URI /edit-game/zombi-2014 to execute the action handler method.

Advertisements

2 thoughts on “SEO Friendly URL in Struts 2

  1. I’m getting error in @Action -> annotation. Is there any dependency or import needed? I’ve added some dependency, But didn’t get any solution. Please Help.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s