Struts2在验证失败时重新填充表单信息

时间:2013-07-22 14:20:22

标签: java validation struts2 field repopulation

我有一个页面,其中包含预先填充了用户信息的表单。这是一个用户个人资料页面。我已对某些字段进行了验证,但目前我的验证方法只是硬编码来执行addFieldError("exp", "Cats");,其中exp是一个正在验证的变量,而Cats是一个随机消息。表单有选择和双重选择,我通过在jsp中执行操作来重新填充。 (见下文)

这是整个表格:

<s:form action="%{formAction}" method="post" enctype="multipart/form-data">
    <div id="buttons">
        <s:submit value="Save" />
    </div>

    <div id="left_column" class="divStyle">
            <div id="picture">
                <div id="picture_border">
                    Picture should go here 150px x 150px
                </div>
                <s:file name="upload" label="File" />
            </div>

            <hr />  

            <div id="contact" class="divPad">
                <h3>Contact Information</h3>
                <s:textfield name="email" value="%{profile.email}" required="true" />
            </div>

            <hr />

            <div id="availabilityDuration" class="divPad">
                <h3>When Available</h3>
                    <s:textfield name="whenAvailable" value="%{profile.whenAvailable}" />

                <h3>Availability Length</h3>
                <s:textfield name="availabilityLength" value="%{profile.availabilityLength}" />

                <h3>Desired Credit</h3>
                <s:action name="CreditSelectAction" executeResult="true" />
            </div>
        </div>


        <div id="right_column" class="divStyle">
            <div id="basic_info" class="divPad">
            <h4>College & Major</h4>
            <s:action name="CollegeMajorsSelectAction" executeResult="true" />
            <hr />
            <h4>Years of Work Experience</h4>
            <s:action name="ExpYearsSelectAction" executeResult="true" />               <hr />
            <h4>Undergrad</h4>
            <s:action name="UndergradSelectAction" executeResult="true" />              <hr />
            <h4>Graduation Year</h4>
            <s:action name="GradYearSelectAction" executeResult="true" />
        </div>

        <hr />

        <div id="aboutDescription" class="divPad">
            <h3>About Me</h3>
                <s:textarea name="comments" value="%{profile.comments}" cols="40" rows="10" />
        </div>

        <hr />

        <div id="skillsNeeds" class="divPad">
            <h3>Skills</h3>
            <div id="userSkillList">
                <s:iterator value="profile.skills" status="status">
            <div>
                    <h5 class="formLabels">Skill Description</h5>
                <s:textfield name="userSkillDescription_%{#status.count}" value="%{description}" />

                <h5 class="formLabels">Years of Experience</h5>
                <s:textfield name="userSkillExperience_%{#status.count}" value="%{experience}"/>

                <h5 class="removeSkillLink" onclick="removeUserSkill(this);">Remove Skill</h5>
            </div>
        </s:iterator>
        <h5 class="addSkillLink" id="addSkill" onclick="addUserSkill();">Add New Skill</h5>
    </div>  
</div>

</div>
</s:form>

下拉列表正常填充。问题是当我重新加载jsp时,我认为将保存在值栈中并在重新加载jsp(%{formAction}%{profile.email}等)时保留的值不会被保留。如何在验证失败后重新加载页面时捕获这些值并显示它们?我已经尝试将它们添加到会话中,但这往往会变得混乱,我不知道如何使用formAction

来自struts.xml的代码:

<action name="updateProfile" class="profiles.actions.UpdateProfileAction" method="execute">
        <!-- <interceptor-ref name="basicStack"/>
        <interceptor-ref name="fileUpload">
            <param name="allowedTypes">image/jpeg,image/gif,image/png,image/jpg</param>
        </interceptor-ref> 
        <interceptor-ref name="validation"/>
        <interceptor-ref name="workflow"/> -->
        <result name="success">/index.jsp</result>
        <result name="input">/jsp/editProfile.jsp</result>
    </action>

加载表单的Action中的代码段:

public String execute()
{

    // get the user profile
    String result = "success";

    //If the profile is null, then the user is new and does not yet have a profile
    //NOTE: If the user's profile doesn't exist, when trying to view someone else's 
    //profile, they will be redirected to edit their own.
    if(user.intValue() == 0)
    {
        logger.info("New User Detected. Returning Failure.");
        result = "failure";
    }
    else
    {
        //If the userid is null, we are loading the user's profile
        //Otherwise, we are viewing someone else's profile

        if(userid == null)
            userid = user.toString();

        profile = dao.selectCurUserById(Integer.parseInt(userid));

        // get all of my projects
        this.setMyProjects(projectDAO.selectMyProjects(Integer.parseInt(userid)));

        // get all of the projects i've been invited to
        this.setJoinedProjects(projectDAO.selectJoinedProjects(Integer.parseInt(userid)));
    }
    return result;

}

来自该操作的代码片段,用于更新用户个人资料:

public String execute()
{
    // request that sent from the client
    HttpServletRequest request = ServletActionContext.getRequest();
    Map<String, Object> session = ActionContext.getContext().getSession();

    profile = new UserProfile();
    id = ((authentication.beans.User) session.get("currentUser")).getId();
    profile.setId(id);
    profile.setEmail(email);
    profile.setAvailabilityLength(availabilityLength);
    profile.setComments(comments);
    profile.setUndergrad(Integer.parseInt(undergrad));
    profile.setWhenAvailable(whenAvailable);
    profile.setYear(year);
    profile.setCredit(credit);
    profile.setMajor(Major.getMajor(major));
    profile.setCollege(College.getCollege(college));
    profile.setExp(exp);
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
    profile.setModify(sdf.format(new GregorianCalendar().getTime()));

    //If file is not null, then the user is uploading an image for his/her
    //profile
    if(file != null)
    {
        byte[] b = new byte[(int) file.length()];
        try
        {
            new FileInputStream(file).read(b);
            b = Base64.encode(b);
        } 
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            profile.setComments(profile.getComments() + "\n" + e.getMessage());
        }
        profile.setPic(b);
    }

    // get all of the params and then process the user skills
    HashMap<String,String[]> params = (HashMap<String,String[]>)request.getParameterMap();

    // process the user skills
    profile.setSkills(processSkills(params));

    // add the userid to the skills
    for(int i = 0; i < profile.getSkills().size(); i++){
        profile.getSkills().get(i).setUserID(profile.getId());
    }

    //TODO: Check the result and do error handling
    boolean result = dao.updateProfile(profile);

    return "success";
}

更新

问题几乎就是coding_idiot所说的。在加载表单的操作中,我需要获取信息的getter以初始填充表单(有此)。在更新信息的操作中,我需要为表单中的信息设置setter,如果在验证失败后应重新填充表单,则需要获取新信息的getter。我通过使用从表单获得的数据填充更新操作中profile函数中的validate()对象,然后为profile对象提供setter来解决此问题。我没有对我的.jsp进行任何更改

1 个答案:

答案 0 :(得分:0)

我不知道你在行动中写了什么,但从上面我可以推断这是对功能问题的轻微误解。你有字段的字段 - 电子邮件,whenAvailable等,但它们的值是从配置文件对象中获取的。

您如何期望从不存在的东西中设置它?

To make it more clear : 
Values that go from JSP to action is email, but what comes back is profile.email, instead it 
should have been just email, or you can simply skip the value attribute or you can change your 
field-name to profile.email

如果有帮助,请告诉我。

[编辑]

再次阅读你的问题,配置文件的getter和setter将无济于事,因为什么 进入动作只是原始字段(电子邮件等)所以你应该为这些字段设置getter / setter,然后将字段重新填充到JSP中 你可以简单地用于例如:

 <s:textfield name="whenAvailable" value="%{whenAvailable}" />

OR

 <s:textfield name="whenAvailable"/>