September 30, 2011

Accessing request headers in a Struts 2 action

1) Create an action class - HeaderReader.java - in the src folder of the web application

package info.icontraining.struts2;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class HeaderReader extends ActionSupport implements ServletRequestAware {

   private HttpServletRequest request;
 
   public void setServletRequest(HttpServletRequest request) {
      this.request = request;
   }
 
   public String execute() {

      Enumeration e = request.getHeaderNames();
      String headerName = null;

      while(e.hasMoreElements()) {
         headerName = (String) e.nextElement();
         System.out.println(headerName + ": "); 
         System.out.println(request.getHeader(headerName) + "\n");
      }

      return SUCCESS;
   } 
}

2) Add a headers.html file to the WebContent folder of the web application

<html>
<body>
Check Server console log for Header names and values
</body>
</html>

3) Configure the action class in the struts.xml configuration file

<action name="headerReader" class="info.icontraining.struts2.HeaderReader">
   <result>headers.html</result> 
</action>

4) Test the example by accessing the following URL,

http://localhost:8080/WebAppName/headerReader.action

No comments:

Post a Comment