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;
}
}
try this
HttpServletRequest request = ServletActionContext.getRequest() ;
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With