my dog learned polymorphism
The moose likes Struts and the fly likes returning user defined strings in Struts 2 action classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "returning user defined strings in Struts 2 action classes" Watch "returning user defined strings in Struts 2 action classes" New topic

returning user defined strings in Struts 2 action classes

Rajiv Chelsea
Ranch Hand

Joined: Jun 15, 2010
Posts: 88
How can i achieve the following?
As we know Struts 2 action classes have an execute method which returns a string.In my action class execute method, I call a method which returns a page name as a string.. the page name will be different as per the business logic.

How can i return the page string and map it in struts.xml ?

Thanks in advance.
Joe Ess

Joined: Oct 29, 2001
Posts: 9190

I'm not sure I understand your problem. Struts doesn't care what you return from execute as long as it matches a result in struts.xml and Struts doesn't care what you name results.

[How To Ask Questions On JavaRanch]
ryan sukale
Ranch Hand

Joined: Aug 11, 2007
Posts: 53
Hi Rajiv,

Yes, you can return dynamic pages from your struts 2 action. The idea here would be to save the page name in an instance variable in the action, and create a getter/setter for it. Then in your action mapping, you can use the above created getter for your page name.

I created some quickie dummy actions and results just for elaboration purpose. So the naming might look a little bit eerie. Just bear with it.

Check out the following code for the action class.

I will be invoking the "anotherMethod" function in my action mapping that follows. If you wish to, you can use the the code written in the "anotherMethod" function inside the execute method itself.
Here's the action mapping.

As you can see, i returned a "success" string from my "anotherMethod" in the action class. So, the above result will be invoked on completion of the action. The page to be displayed is evaluated as an EL variable and fetches the nextPage property on the DummyAction2 class
The action invocation is just as usual.

I guess, you can let your business logic determine the page name. And you page will be displayed accordingly based upon the value set in a field in the action.

Hope this helps ;)

Ryan Sukale

SCJP 5.0, SCWCD 5.0, SCBCD 5.0
I agree. Here's the link:
subject: returning user defined strings in Struts 2 action classes
It's not a secret anymore!