Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struts2: How do i get ServletRequest instance in ActionSupport

How do I get the ServletRequest instance in my action?

I implemented ServletRequestAware but I am not able to get request object in the action.

struts.xml

<package name="default" extends="struts-default,json-default">
    <action name="Cart"
    class="struts.cart.action.CartAction">
        <interceptor-ref name="json">
            <param name="contentType">application/json</param>
        </interceptor-ref>
        <result type="json"/> 
    </action>   
</package>

I am making call using Ajax/JavaScript:

req.onreadystatechange = onReadyState;  
req.open(POST, Cart.action, false);  
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");  
req.send(JSONstr);

JSON object:

var data = { cartItem: {
     modelNo: $('#modelNo').val(),
     description: $('#description').val(),
     price: $('#price').val(),
     action: $('#action').val(),
     quantity: $('#quantity').val()
}};
JSONstr = JSON.stringify(data);

Action:

public class CartAction extends ActionSupport implements  ServletRequestAware {

    private HttpServletRequest request;
    private Map cartItem = new HashMap();

    public String execute() throws Exception {
        System.out.println("request  " + cartItem); // getting here cartitem
        System.out.println("request  " + request);  // request  null 
    }

    public void setServletRequest(HttpServletRequest httpServletRequest) {
        this.request = httpServletRequest;
    }

    public Map getCartItem() {
        return cartItem;
    }

    public void setCartItem(Map cartItem) {
        this.cartItem = cartItem;
    }

}   
like image 715
ved prakash Avatar asked Feb 26 '13 15:02

ved prakash


2 Answers

try this

HttpServletRequest request = ServletActionContext.getRequest() ;
like image 104
PSR Avatar answered Nov 07 '22 06:11

PSR


  1. Why do you need the servlet request? It's rare it's required.
  2. The reason ServletRequestAware isn't working is because you removed the interceptor that sets it into the action:
<action name="Cart" class="struts.cart.action.CartAction">
  <interceptor-ref name="json">
    <param name="contentType">application/json</param>
  </interceptor-ref>
  <result type="json"/> 
</action>   

When you set any interceptors in an action's configuration you must set all interceptors.

Here you've removed all the default interceptors, including "servletConfig" which sets the request for ServletRequestAware actions, and are running only the json interceptor.

like image 30
Dave Newton Avatar answered Nov 07 '22 05:11

Dave Newton