umairaslam
umairaslam

Reputation: 377

Store form values in a bean in action class

Let's say we have a JSP like this:

<s:form action="MyActionClass" namespace="/sec">
    <s:hidden name="userId" value="%{userId}"
    <s:textfield name="name" value="%{name}" label="Name" />
    <s:textfield name="location" value="%{location}" label="Location" />
</s:form>

And an action class like this:

public class MyActionClass extends ActionSupport {
    private String userId;
    private String name;
    private String location;
//getters and setters
}

This works fine and I get values in the action fields from jsp on submitting form. What I want to do is make another bean class, put the fields in that bean class, declare the bean class as the property of action class and populate its fields. Something like this.

public class MyActionClass extends ActionSupport {
    private UserDTO user;
//getters and setters
}

And the UserDTO class looks like this.

public class UserDTO{
    private String userId;
    private String name;
    private String location;

public UserDTO(){
}
//getters and setters
}

I have tried doing this:

 <s:form action="MyActionClass" namespace="/sec">
    <s:bean name="com.actions.DTOs.UserDTO" var="user">
       <s:hidden name="user.userId" value="%{user.userId}"
       <s:textfield name="user.name" value="%{user.name}" label="Name" />
       <s:textfield name="user.location" value="%{user.location}" label="Location" />
    </s:bean>
</s:form>

Upvotes: 1

Views: 4503

Answers (1)

AsSiDe
AsSiDe

Reputation: 1846

Try This:

Your Form jsp:

<s:form action="MyActionClass" namespace="/sec">
    <s:textfield name="user.userId" value="" label="UserId" />
    <s:textfield name="user.name" value="" label="Name" />
    <s:textfield name="user.location" value="" label="Location" />
    <s:submit/>
</s:form>

MyActionClass.java :

public class MyActionClass extends ActionSupport implements ModelDriven<UserDTO>{

private UserDTO user;

public UserDTO getUser() {
    return user;
}


public void setUser(UserDTO user) {
    this.user = user;
}

@Override
public String execute() throws Exception {

    return SUCCESS;
}

}

struts.xml configuration:

<struts>

<constant name="struts.devMode" value="true"></constant>

<package name="mypackage" namespace="/sec" extends="struts-default">
    <action name="actionWhichResultsToYourFormJSPHere">
        <result>yourFormJspHere.jsp</result>
    </action>
    <action name="MyActionClass" class="sec.MyActionClass">

        <result name="success">/result.jsp</result>
    </action>
</package>
</struts>

your result.jsp:

<body>
    id=${user.userId}<br>
    name=${user.name}<br>
    location=${user.location}<br>
</body>

Upvotes: 2

Related Questions