在 Struts 2 中将值从 Action 传递到模型

Passing values from Action to model in Struts 2

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

我的情况:

  1. 我从请求 url 中获取了一个参数。
  2. 我使用此值生成我自己的对象class - 产品(我在执行方法中执行)。
  3. 然后我想将 Product class 对象列表注入 jsp 视图。

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

我对 Action class 的实施:

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;
}

很像您指定 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;
  }      
}