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

Java Struts2在验证失败时重新填充表单信息,java,validation,struts2,field,repopulation,Java,Validation,Struts2,Field,Repopulation,我有一个带有表单的页面,该表单预先填充了用户信息。这是一个用户配置文件页面。我已经对一些字段进行了验证,但目前我的验证方法只是硬编码来执行addFieldError(“exp”,“Cats”)其中exp是一个正在验证的变量,而CAT是一条随机消息。表单有select和doubleselect,我通过在jsp中执行操作来重新填充它们。(见下文) 这是整个表格: <s:form action="%{formAction}" method="post" enctype="multipart/fo

我有一个带有表单的页面,该表单预先填充了用户信息。这是一个用户配置文件页面。我已经对一些字段进行了验证,但目前我的验证方法只是硬编码来执行
addFieldError(“exp”,“Cats”)其中
exp
是一个正在验证的变量,而CAT是一条随机消息。表单有select和doubleselect,我通过在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>
加载表单的操作的代码段:

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";
}
publicstringexecute()
{
//从客户端发送的请求
HttpServletRequest=ServletActionContext.getRequest();
映射会话=ActionContext.getContext().getSession();
profile=newuserprofile();
id=((authentication.beans.User)session.get(“currentUser”).getId();
profile.setId(id);
设置电子邮件(电子邮件);
profile.setAvailabilityLength(availabilityLength);
资料.评论(评论);
profile.setUndergrad(Integer.parseInt(undergrad));
profile.setWhenAvailable(whenAvailable);
设定年份(年);
资料:setCredit(信用);
设置专业(专业)设置专业(专业);
个人资料.setCollege(College.getCollege(College));
setExp(exp);
SimpleDataFormat sdf=新SimpleDataFormat(“年月日”);
setModify(sdf.format(新的gregorianalendar().getTime());
//如果文件不为空,则用户正在上载他/她的图像
//侧面图
如果(文件!=null)
{
字节[]b=新字节[(int)file.length()];
尝试
{
新文件输入流(file).read(b);
b=Base64。编码(b);
} 
捕获(IOE异常)
{
//TODO自动生成的捕捉块
profile.setComments(profile.getComments()+“\n”+e.getMessage());
}
资料.setPic(b);
}
//获取所有参数,然后处理用户技能
HashMap params=(HashMap)request.getParameterMap();
//处理用户技能
设定技能(过程技能(参数));
//将用户ID添加到技能中
对于(int i=0;i
更新


问题和你的白痴说的差不多。在加载表单的操作中,我需要有用于最初填充表单的信息的getter(had this)。在更新信息的操作中,我需要为放入表单中的信息设置setter,并为在验证失败后重新填充表单时从何处获取新信息设置getter。我用从表单中获得的数据填充更新操作中的
validate()
函数中的
profile
对象,然后为
profile
对象提供一个setter,从而解决了这个问题。我不需要对我的.jsp进行任何更改,我不知道您在操作中写了什么,但从上面我可以推断,这是对功能问题的一个轻微误解。您的字段名为email、whenAvailable等,但它们的值是从profile对象获取的

你怎么能指望从根本不存在的东西上设置它呢

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}" />



应保留它们;您是否使用
重定向操作
为您
输入
结果?操作中的
配置文件
对象是否有getter和setter?我没有使用
重定向操作
。我确实有
配置文件
对象的getter和setter。这可能是个问题。我还没有尝试过,但这是如何解释
formAction
设置不正确的原因呢?因为formAction从来没有作为请求参数提交过!您只需创建一个隐藏字段来提交formAction,然后当它返回时,它将自动填充。我添加了
只是为了得到相同的结果。加载的jsp中的表单显示了
,您需要先设置formAction,以便它对jsp正常运行,然后由于该隐藏字段而返回。此隐藏字段之前formAction的值是多少。它最初设置正确,因为如果它正确验证,我可以进行更新。在本例中,它被设置为
 <s:textfield name="whenAvailable" value="%{whenAvailable}" />
 <s:textfield name="whenAvailable"/>