Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ActionForm in Struts 2?

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?

like image 465
Ravi Gupta Avatar asked Nov 10 '22 21:11

Ravi Gupta


1 Answers

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.

like image 148
Roman C Avatar answered Nov 15 '22 09:11

Roman C