tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Struts2 > Basic > Access Request and Response

Access Request and Response 

Struts2 does'nt allow to directly access HttpServletRequest and HttpServletResponse object. This increases the testability and test stub generating becomes easier. However in some cases we need to directly interact with request and response. Struts2 provides two interface (ServletRequestAware and ServletResponseAware) which helps to get a handle of request and response objects.

This example shows accessing HttpServletRequest and HttpServletResponse in Struts2. The necessary libraries are shown below,


The required interfaces to implement are shown below,
File Name  :  
public abstract interface ServletRequestAware
  public abstract void setServletRequest(HttpServletRequest paramHttpServletRequest);

public abstract interface ServletResponseAware
  public abstract void setServletResponse(HttpServletResponse paramHttpServletResponse);

Action class implements both interfaces and keeps a reference to request and response. Struts ServletConfigInterceptor sets both request and response objects just before invoking action method on Action class.

File Name  :  
package demo;

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

public class AccessRequest extends ActionSupport implements
ServletRequestAware, ServletResponseAware{

  private static final long serialVersionUID = -6569011111412307537L;
  private HttpServletRequest paramHttpServletRequest;
  private HttpServletResponse paramHttpServletResponse;

  public String execute() {
    System.out.println("Request: " + paramHttpServletRequest);  
    System.out.println("Request parameter 'name' : " + paramHttpServletRequest.getParameter("name"));
    System.out.println("Response: " + paramHttpServletResponse);  
    return SUCCESS;
  public void setServletRequest(HttpServletRequest paramHttpServletRequest){
    this.paramHttpServletRequest = paramHttpServletRequest;

  public HttpServletRequest getServletRequest(){
    return paramHttpServletRequest;

  public void setServletResponse(HttpServletResponse paramHttpServletResponse){
    this.paramHttpServletResponse = paramHttpServletResponse;

  public HttpServletResponse getServletResponse(){
    return paramHttpServletResponse;

Home page is shown below,

File Name  :  

Demo Project Download (4 KB)

Demo Libs Download (3 MB)

bl  br