Reputation: 169
I want the URL of the below format
rather than
http://localhost/users?name=abc
How to achieve this in Struts2?
Upvotes: 2
Views: 2057
Reputation: 653
We can achieve this using struts2. All you need to do is, use wildcard characters in your action name. Let me explain with your case
http://localhost/users/Santhosh
This is what you wanted as the end URL. And you would want to capture the value i.e.; "Santhosh" in action support.
I'm assuming that you're ready to add a struts2 suffix at the end i.e.; ".action" or ".html" (I've customized my action classes extension as .html).
Just define the mapping as below in struts.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<constant name="struts.action.extension" value="html" />
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<action name="users/*" class="com.srm.action.UserAction" method="execute">
<param name="userName">{1}</param>
<result name="success" type="tiles">addEditCategory</result>
</action>
</struts>
If you observe above mapping, "struts.enable.SlashesInActionNames" should be set "true" in order to achieve this.
Here the action support class
public class UserAction extends ActionSupport
{
private static final long serialVersionUID = 1L;
private String userName = null;
public String execute() throws Exception
{
System.out.println("Username: "+userName);
return SUCCESS;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getUserName()
{
return userName;
}
}
After executing this program, you'll get "Santhosh" value populated into userName property.
Upvotes: 0
Reputation: 570365
You could use the REST Plugin or the convention plugin (see this blog post for more details on the later solution). Other options include servlet filtering or mod_rewrite.
Upvotes: 2