marknorkin
marknorkin

Reputation: 4074

Struts how to prepopulate edit form with object

I have a simple entity called Brand:

public class Brand{
    private long id;
    private String name;
    //getters and setters
}

I have a jsp where this data displayed:

        <p>
            <label for="id"><s:text name="brand.view.id" /></label>
            <c:out value="${requestScope.brand.id}"></c:out>
        </p>
        <p>
            <label for="name"><s:text name="brand.view.name" /></label>
            <c:out value="${requestScope.brand.name}"></c:out>
        </p>
        <p>
            <s:a action="edit_display" namespace="/brand"><s:text name="brand.view.button.edit" />
            </s:a>
        </p>

And in this jsp page you see that there is a button "Edit" that will get user to ther editing form. I want this form to be populated with Brand data.

Now in struts.xml I have the next mapping:

<package name="brand" namespace="/brand" extends="struts-default">
        <action name="*_display">
            <result name="success" type="dispatcher">/WEB-INF/view/brand/{1}.jsp
            </result>
        </action>
        <action name="view" class="com.example.action.brand.ViewBrandAction">
            <result name="success">/WEB-INF/view/brand/view.jsp</result>
        </action>
        <action name="edit" class="com.example.action.brand.EditBrandAction">
            <result name="success">/WEB-INF/view/brand/edit.jsp</result>
        </action>
</package>

So the logic now is the next: When User clicks on /brand/edit_display link no action will be called and thus empty form will be displayed.

What options do I have if I want to pass objects beetween jsp's ? Action Chaining, ajax on edit page, another action PopulateEditBrandAction, build query param string or maybe there is something better ?

Because I know the object that user want to edit - can I just simply pass it ?

Upvotes: 0

Views: 887

Answers (1)

Stefan Bartel
Stefan Bartel

Reputation: 190

The call to edit_display creates a new request with a new action context. If you want different requests to share the same data, you have to use the session.

The Struts2 way to do it would be to implement org.apache.struts2.interceptor.SessionAware in your Action.

Save the object in ViewBrandAction:

userSession.put("some_namespace_brand", brand);

Then you can access your object in the jsp by using:

<s:property value="#session.some_namespace_brand.id" />

Or implement what you called PopulateEditBrandAction to get the object back:

brand = (Brand) userSession.get("some_namespace_brand");

Be sure to read the documentation on this as it addresses the security risks of making the session accessible through a request parameter. https://struts.apache.org/docs/http-session.html

Upvotes: 1

Related Questions