【问题标题】:Passing values from Action to model in Struts 2将值从 Action 传递到 Struts 2 中的模型
【发布时间】:2016-07-28 16:46:32
【问题描述】:

我试图弄清楚如何将在 Action 类中创建的值传递给模型(在我的例子中是 jsp 视图)。我是 Struts 2 框架的新手。

我的情况:

  1. 我从请求 url 中得到一个参数。
  2. 我使用这个值来生成我自己的类的对象 - Product(我在执行方法中这样做)。
  3. 然后我想将 Product 类对象列表注入到 jsp 视图中。

我的问题是 - 如何在 jsp 视图中插入我自己的类的对象。

我对 Action 类的实现:

public class ProductAction extends ActionSupport {

private int n;

public int getN() {
    return n;
}

public void setN(int n) {
    this.n = n;
}

public String execute() throws Exception {
    List<Product> products = Service.getProducts(n);//I want to inject this to jsp view
    return SUCCESS;
}

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整和可验证的示例。

标签: java web-applications struts2


【解决方案1】:

就像您指定 setter 将传入参数注入您的 ProductAction 一样,您需要公开您希望在您选择的视图技术中可用的参数,无论是jsp、ftl、vm等。为此,您需要提供一个getter

public class ProductAction extends ActionSupport {
  private Integer n;
  private Collection<Product> products;

  @Override
  public String execute() throws Exception {
    // you may want to add logic for when no products or null is returned.
    this.products = productService.getProducts( n );
    return SUCCESS;
  }

  // this method allows 'n' to be visible to the view technology if needed.
  public Integer getN() {
    return n; 
  }

  // this method allows the request to set 'n'
  public void setN(Integer n) {
    this.n = n;
  }

  // makes the collection of products visible in the view technology.
  public Collection<Product> getProducts() {
    return products;
  }      
}

【讨论】:

  • 感谢您的清晰解释。提供 getter 后,所需的对象在视图中可见 :)
猜你喜欢
  • 2013-06-11
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 2014-07-16
  • 1970-01-01
相关资源
最近更新 更多