|

Doing a Page Redirect from a Java Struts2 Action Class

struts2Logo

I began working on a web site written in Java using Struts2. I wrote a general purpose class to be used by the application. One method in the class was supposed to check if the user was logged in. If not, redirect to the logon page (I did NOT want to add a tag entry to every <action> block in the struts.xml file)!

I searched the web and did not find anything that worked quite right. Finally, after some experimentation, I got something working! Here is some sample code for you:

Helper Class myExample.java:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.*;
import javax.servlet.http.*;

public class myExample {
   public void doARedirectToGoogle() {
      HttpServletResponse response = ServletActionContext.getResponse();
      
      try {
         response.sendRedirect("http://google.com");
      } catch (IOException e) {
         e.printStackTrace();
      } // end of try / catch
   } // end of doARedirectToGoogle() method
} // end of myExample class

Note the try/catch block must be in place in order for this to compile and work.

Struts2 Action Class:  demoPage.java:

import com.chomer.demo;

public class demoPage extends ActionSupport {
   public String execute() {
      myExample demo = new myExample();
      demo.doARedirectToGoogle();
      
      return "success";
   } // end off execute() method
} // end of demoPage class

Action Block added to struts.xml:

<action name="demoPage" method="execute" class="com.chomer.actions.demoPage">
   <result name="success">/pages/demoPage.jsp</result>
   <result name="error">/pages/demoPageErr.jsp</result>
</action>

Success Page… demoPage.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<html>
   <body>
      <h1>This page will come up if the redirect does not work!</h1>
   </body>
</html>

Failure Page… demoPageErr.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<html>
   <body>
      <h1>This page will come up if the redirect does not work AND there was an error!</h1>
   </body>
</html>

In the above example I made up some arbitrary packages names. You will have your own structure in place. If this works you should never see the success or failure page.

In a real world scenario, the redirect would happen only if a certain condition was being met (such as the user is not logged in). If the user were logged in, demoPage.jsp’s contents would appear.

Similar Posts