Struts2: How to get a ServletRequest instance in ActionSupport

How do I get an instance ServletRequestin my actions?

I implemented ServletRequestAware, but I can not get the request object in 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 a 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);

Act:

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;
    }

}   
+5
source share
3 answers

try it

HttpServletRequest request = ServletActionContext.getRequest() ;
+5
source
  • Why do you need a servlet request? This was rarely required.
  • The reason ServletRequestAware does not work, because you removed the interceptor that sets it into 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 install any interceptors in the action configuration, you must install all interceptors.

, "servletConfig", ServletRequestAware json.

+4

AjaxActionSupport ActionSupport .

public class TestAjaxAction extends AJAXActionSupport {

// inside this you are executing a method where you can easily get both objects.

public void perform (HttpServletRequest request, HttpServletResponse response) throws an AJAXActionException {

0
source

All Articles