If we want execute a business logic only when a user has been authenticated we need to introduce an interceptor as best practice.

On struts.xml we define

<interceptor name="login"
class="com.AuthInterceptor" ></interceptor>
<interceptor&minus;stack name="defaultLoginStack">
<interceptor&minus;ref name="servletConfig" ></interceptor>
<interceptor&minus;ref name="params" ></interceptor>
<interceptor&minus;ref name="login" ></interceptor>
<interceptor&minus;ref name="pageConfig" ></interceptor>
<interceptor&minus;ref name="prepare" ></interceptor>
<interceptor&minus;ref name="chain" ></interceptor>
<interceptor&minus;ref name="modelDriven" ></interceptor>
<interceptor&minus;ref name="fileUpload" ></interceptor>
<interceptor&minus;ref name="staticParams" ></interceptor>
<interceptor&minus;ref name="params" ></interceptor>
<interceptor&minus;ref name="conversionError" ></interceptor>
<interceptor&minus;ref name="validation" ></interceptor>
<interceptor&minus;ref name="workflow" ></interceptor>
<action name="MyPage" class="com.MyPageAction">
<interceptor&minus;ref name="defaultLoginStack"></interceptor&minus;ref>

Ok, let’s go to view the code of our interceptor

package interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class AuthInterceptor implements Interceptor
    private static final long serialVersionUID = 2756130976196611906L;
    public void destroy()
        // TODO Auto-generated method stub
    public void init()
        // TODO Auto-generated method stub
    public String intercept(ActionInvocation invocation) throws Exception
        final ActionContext context = invocation.getInvocationContext();
        // we add a simple auth logic for example
        String auth = (String) context.getSession().get("AUTH");
        if (auth == null)
            // no auth found so we redirect to login result
            return "login";
            // user authenticated so we can execute the business logic of our action
            return invocation.invoke();

In this way only user that correctly pass through AuthInterceptor will execute the logic and the flow of action requested, the other will be redirected to login result.

Share →

Leave a Reply

Your email address will not be published. Required fields are marked *