1

Can any one please explain how to use checkbox interceptor. Here my problem is i have to save the checkbox value as 'Y' if it was checked other wise 'N' at the same time when i am viewing the details which are coming form database if the value of checkbox is 'Y' it has to be checked otherwise it should not checked.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Jagadeesh
  • 87
  • 1
  • 13

1 Answers1

3

In your getter setter put conversion code

private String mycheckbox;

public String execute(){
    //In action you will always get 'Y' or 'N' 
    System.out.println("In action mycheckbox :"+mycheckbox);
    return SUCCESS; 
}

public void setMycheckbox(String mycheckbox) {
    if(mycheckbox.equalsIgnoreCase("false"))
    {
        this.mycheckbox="N";    
    }
    else
    {
    this.mycheckbox = "Y";
    }
}

public String getMycheckbox() {
    if(mycheckbox.equalsIgnoreCase("N"))
    {
        //In JSPs you will always get true or false
        this.mycheckbox="false";    
    }
    else
    {
    this.mycheckbox = "true";
    }
    return mycheckbox;
}

In JSP

<s:checkbox name="mycheckbox" id="mycheckbox"  />

So in action you will get 'Y' and 'N' But for struts tags it will use true or false. and check box will get selected if 'Y' is there.

So above solution will work for your problem.

You can use the same logic with interceptors too but I think getter setter is the easiest way because you will have getter setters compulsorily in action.

How CheckboxInterceptor works??

When you write

<s:checkbox name="mycheckbox" id="mycheckbox" fieldValue="Y" />

Generated Html is

 <input id="mycheckbox" type="checkbox" value="Y" name="mycheckbox"></input>

 <input id="__checkbox_mycheckbox" type="hidden" value="Y" name="__checkbox_mycheckbox"></input>

Now you can see it generated hidden field. So the fieldvalue Y you will get in value="Y" of checkbox.

Case 1: if checkbox is selected in action in mycheckbox variable.

In action mycheckbox :Y (because of value="Y" in <input id="mycheckbox"..>)

If checkbox is not selected

In action mycheckbox :false

case 2: But if this checkbox isn't submitted

CheckBoxInterceptor will come in picture it will scan parameter with _checkbox prefix and does what -> it sets value to false So eventhough there were no value in hidden field action will get some value i.e. false

So if selected fieldValue will be returned to action variable and if not selected it will set false to it.

Here you can specify setUncheckedValue("N"); So you can get N in __checkbox_mycheckbox but not in mycheckbox variable. mycheckbox will return false only.

But one thing you need to keep in mind that checkbox value is converted to boolean only So even though you will set this you will get the value "N" in __checkbox_mycheckbox not in mycheckbox.

prem30488
  • 2,828
  • 2
  • 25
  • 57