Jagadeesh
Jagadeesh

Reputation: 852

key attribute OGNL issue in Struts2

I have been working with Struts2 for a long time.

When I use <s:textfield label="Product Id" key="%{productId}"/> or <s:textfield label="Product Id" key="[0].productId"/> it is not working. i.e. If I use first tag with key attribute pointing to OGNL expression %{productId} then the resulted html input tag's name attribute is coming as empty.i.e. <input type="text" name="" value="" id="Product_Save_"/>. If I use <s:textfield label="Product Id" key="[0].productId"/> tag then the resulted html input tag is <input type="text" name="[0].productId" value="" id="Product_Save__0__productId"/>.

In the both the cases Struts is not able to populate my request parameter into my model object which is product class which is as below:

public class Product{

private String productId;
private String productName;
private int price;
private ProductOwner productOwner;

public Product() {}

public Product(String productId, String productName, int price) {
    this.productId = productId;
    this.productName = productName;
    this.price = price;
}

public void setProductOwner(ProductOwner productOwner) {

    this.productOwner = productOwner;
}

public ProductOwner getProductOwner() {
    return productOwner;
}

public String getProductId() {
    return productId;
}

public void setProductId(String productId) {
    this.productId = productId;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

}

If I use <s:textfield label="Product Id" key="productId"/> then Struts is able to populate the productId into Product class productId.

But when I use <s:property value="%{[0].productId}"/> it is working properly.

Now my question is why I can not use full OGNL expressions like %{[0].productId}, But in <s:property /> tag Why I can use full OGNL expressions like %{[0].productId}.

Upvotes: 1

Views: 626

Answers (1)

Aleksandr M
Aleksandr M

Reputation: 24396

The key="%{productId} doesn't work because by using %{} you are forcing expression evaluation and you don't have value in productId so name attribute is empty.

The key="[0].productId" is a correct expression and normally would work in OGNL, but because it has certain security risks it is not allowed to use this expression to set values in Struts2. Of course it is allowed to get values by this expression so <s:property value="[0].productId"/> works.

Upvotes: 1

Related Questions