Struts 2 - 使用Object的Attributes预填充表单

时间:2016-06-08 11:21:42

标签: java jsp struts2

我想使用Struts 2标记预先填充表单,其中包含我从会话中收到的对象的属性值。

PromoCode promoCode = (PromoCode) session.getAttribute("PROMOCODE");


我试过这种方法,但它没有用。

<s:form action="add">
            <s:select label="Ticket Name " name="ticketName" list="{'PARTY PLATINUM', 'INAUGURATION PREMIUM'}"></s:select>
            <s:textfield label="Promotion Type " value="%{promoCode.promotionType}" name="promotionType"></s:textfield>
            <s:select label="Discount Access " value="promoCode.discountAccess" name="discountAccess" list="{'Choose Your Discount Access', 'Coded Discount', 'Public Discount'}"></s:select>
            <s:textfield label="Name of the Public Discount " name="nameOfPublicDiscount"></s:textfield>
            <s:textfield label="Discount per ticket (%) " value="promoCode.discountPerTicket" name="discountPerTicket"></s:textfield>
            <s:textfield label="Uses per offer " value="promoCode.uses" name="uses"></s:textfield>
            <br/>
            <s:submit id="update" value="UPDATE"></s:submit>
</s:form>


如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

使用getter和setter创建一个promoCode类变量。在Struts2中获取http会话属性,你应该使用一个会话映射,它通过截取SessionAware接口的拦截器注入你的动作bean。

public class MyAction extends ActionSupport implements SessionAware {

  private PromoCode promoCode;
  public PromoCode getPromoCode(){ return promoCode; }
  public void setPromoCode(PromoCode promoCode){ this.promoode = promoCode; }
  private Map<String, Object> session;

  @Override
  public void setSession(Map<String, Object> session) {
   this.session = session;
  } 
  @Override
  public String execute() throws Exception {
    PromoCode promoCode = (PromoCode) session.get("PROMOCODE");
    setPromoCode(promoCode);
    return SUCCESS;
  }

}

在JSP中,您应该将输入字段绑定到操作bean属性。

<s:form action="add">
    <s:select label="Ticket Name " name="promoCode.ticketName" list="{'PARTY PLATINUM', 'INAUGURATION PREMIUM'}"></s:select>
    <s:textfield label="Promotion Type "  name="promoCode.promotionType"></s:textfield>
    <s:select label="Discount Access "  name="promoCode.discountAccess" list="{'Choose Your Discount Access', 'Coded Discount', 'Public Discount'}"></s:select>
    <s:textfield label="Name of the Public Discount " name="promoCode.nameOfPublicDiscount"></s:textfield>
    <s:textfield label="Discount per ticket (%) "  name="promoCode.discountPerTicket"></s:textfield>
    <s:textfield label="Uses per offer " name="promoCode.uses"></s:textfield>
    <br/>
    <s:submit id="update" value="UPDATE"/>
</s:form>