File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Struts and the fly likes how to redirect from prepare() method in struts 2 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "how to redirect from prepare() method in struts 2" Watch "how to redirect from prepare() method in struts 2" New topic

how to redirect from prepare() method in struts 2

Saikat Podder

Joined: Jan 09, 2009
Posts: 5
Hello friends,
I have very little experience in struts 2 & I have this typical requirement where I feel that I have to redirect form the prepare() method when the user is not logged in (by checking whether some session entries present or not).
Actually I am trying to avoid repetitive session checking & redirecting at the beginning of every action method, for example
public String listUsers() throes Exception
//if (session.get("userType") != null && session.get("userType").equals("admin"))
//then show the result
//otherwise redirect to the login page

public String viewDetails() throes Exception
//again code for the same checking
so I thought that since the prepare() method is being called every time some action is being mapped to a method in this class so why not put the code for checking & redirecting inside of prepare
public void prepare() throws Exception
//if the user is not logged in
//redirect to the login page

But the problem is that I cannot return any string (which I can specify as result of type "redirect-action" in the struts.xml file)since this function has return type void also I could not find any method to redirect forcibly.

So, my question is whether it is possible to redirect form any method which has not been mapped as an action at all?
if it can be done then how to do it?

Any ideas regarding this problem would really help.
Thanks in advance
David Newton

Joined: Sep 29, 2008
Posts: 12617

(For those not also following the struts-user mailing list: I replied there and said that this kind of functionality is usually implemented using Struts 2 interceptors.)
I agree. Here's the link:
subject: how to redirect from prepare() method in struts 2
It's not a secret anymore!