2012-01-16 71 views
0

我是Struts2和Hibernate的新成员。我试图从表单中保存值。 关于提交textarea的值将被保存为null;从表格中保存TextArea的值

我的形式是像这个 -

<s:form action="saveComment"> 
         <s:push value="ai"> 
          <s:hidden name="id"/> 
          <table cellpadding="5px"> 
           <tr><td><s:textarea name="description" rows="5" cols="60" theme="simple" /> 
            </td> 
            <td> <s:submit type="image" src="images/sbt.gif" > 

             </s:submit> 
            </td></tr> 

          </table> 
         </s:push> 
        </s:form> 

和我的行动方法就像是这个 -

public String saveComment() throws Exception { 

    Map session = ActionContext.getContext().getSession(); 
    ExternalUser user = (ExternalUser) session.get("user"); 
    AIComment aiComment = new AIComment(); 
    aiComment.setAi(ai); 
    aiComment.setPostedOn(new java.util.Date()); 
    aiComment.setPostedBy(user); 
    aiCommentDao.saveAIComment(aiComment); 
    return SUCCESS; 
} 

回答

0

Struts2的具有建立的机制,所有你需要的表单数据传输到您的尊敬的Action类执行以下步骤。

  1. 在您的动作类中创建与表单字段名称相同的属性并提供getter和setter。

Struts2的将匹配字段的名称那些动作属性名称从形式发送,并会在你的情况下填充他们为你

所有你需要做T以下

public class YourAction extends ActionSupport{ 

    private String id; 
    private String description 

    getter and setters for id and description fileds 

    public String saveComment() throws Exception { 
     //Your Method logic goes here 
    } 

} 

因此,当你提交表单时,它将包含id和描述作为表单值。Struts2拦截器(在这种情况下为param)会看到你的动作类具有这些属性,并且将在saveComment()方法执行之前填充它们。

希望这会给你一些理解。

简而言之,所有这些繁重的工作数据传输/类型转换是由幕后的拦截器完成的。

阅读拦截器的详细信息以便更好地理解

  1. interceptors
  2. parameters-interceptor
0

首先,你行动的名称必须是你的别名的名称。然后你应该指定方法名称。

当然,你应该在struts.xml中

<action name="Comment_*" method="{1}" class="com.yourproject.folder.Comment"> 
     <result name="input">/pages/page.jsp</result> 
     <result name="success" type="redirectAction">nextAction</result> 
    </action> 

所以定义动作和方法,你可以写

<s:form action="Comment_saveComment"> 

而在你的类

public class Comment extends ActionSupport { 

    public String saveComment() throws Exception { 
    Map session = ActionContext.getContext().getSession(); 
    ExternalUser user = (ExternalUser) session.get("user"); 
    AIComment aiComment = new AIComment(); 
    aiComment.setAi(ai); 
    aiComment.setPostedOn(new java.util.Date()); 
    aiComment.setPostedBy(user); 
    aiCommentDao.saveAIComment(aiComment); 
    return SUCCESS; 
    } 
} 

我不知道你如何得到“ai”和“user”的价值。如果您想从FORM中获取值,则必须声明与表单输入名称相同的字符串。在你的情况“id”,“description”是输入值。如果你想从FORM获得值,你应该在你的类中声明这些变量的getter和setter。

在你的情况下,“ID”

private String Id; 
private String Description; 

public String getId() { 
    return Id; 
} 

public void setId(String Id) { 
    this.Id = Id; 
} 

... 
+1

为什么动作的名称应该是类的名字?动作名称是一个别名,没有为此定义规则 – 2012-01-16 06:59:03

+0

是的,你是对的。让我解决它 – batbaatar 2012-01-16 07:02:24