How to get ActionForm in Struts 2?

5k views Asked by At

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?

1

There are 1 answers

9
Roman C On

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 not null, else it will be ignored.

In the action class you have a field that you can use inside.