在Struts 2中将值从Action传递给model

时间:2016-07-28 16:46:33

标签: java web-applications struts2

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

我的情况:

  1. 我从请求网址获取参数。
  2. 我使用这个值来生成我自己的类的对象 - Product(我在执行方法中执行)。
  3. 然后我想将Product类对象列表注入jsp视图。
  4. 我的问题是 - 如何在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;
    }
    

1 个答案:

答案 0 :(得分:0)

就像你如何指定 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;
  }      
}