not auto populating in struts2 form

后端 未结 1 916
一整个雨季
一整个雨季 2021-01-27 00:13

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 whe

相关标签:
1条回答
  • 2021-01-27 01:10

    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.

    0 讨论(0)
提交回复
热议问题