I am migrating an Struts 1 app to Struts2 and trying to minimize the code changes required.
I need to know how to access the ActionForm
in a Struts2 Action
class. Below is my current code and I am getting NPE when trying to access ActionForm
.
Public class DeptBuildingNewAction extends ActionSupport
implements ServletRequestAware, ServletResponseAware, ModelDriven<DeptBuidingFormBean> {
private HttpServletRequest request;
private HttpServletResponse response;
private DeptBuidingFormBean form;
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.request = httpServletRequest;
}
public void setServletResponse(HttpServletResponse httpServletResponse) {
log.debug("Inside setServletResponse");
this.response = httpServletResponse;
}
public DeptBuidingFormBean getModel() {
log.debug("Inside getForm");
return form;
}
public void setModel(DeptBuidingFormBean form) {
log.debug("Inside setForm");
this.form = form;
}
What is the best way to get the ActionForm
over here?
The form (model in Struts2) should be initialized to prevent NPE.
private DeptBuidingFormBean form = new DeptBuidingFormBean();
The ModelDriven
action allows to access a model on the view layer and in action directly from the valueStack
, i.e. without model
or form
prefix.
The modelDriven
interceptor should be on the interceptors stack of the action. The default stack contains this interceptor.
From the docs:
Note: The
ModelDrivenInterceptor
will only push the model into the stack when the model is notnull
, else it will be ignored.
In the action class you have a field that you can use inside.
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