Search code examples
javajspjstlstrutsel

Is it possible to define a variable in Java and use that in JSP code?


I have a drop down like below:

<html:select styleId="colorCodeId" property="msSpec.colorcodeId" name="Form"  styleClass="form-control">
                            <option value="-1"></option>
                            <html:optionsCollection property="colorcodeList" style="background: <%=test1%>;"/>
                        </html:select>

in Java code I have:

List<LabelValueBean> colorcodeList = new ArrayList<LabelValueBean>();
for (Mty property : customPropertyList) {
            LabelValueBean bean = new LabelValueBean(property.getName(), property.getId().toString());

if (property instanceof ColorCode) {
                test1 = property.getName();
                System.out.println("test1: " + test1);
                colorcodeList.add(bean);
            }
}

Is it possible I define test1 like above and use that as a background color in my drop down? Right now it doesn't work.


Solution

  • You can use a JSP EL expression instead of the variable. The reason is to remove scriptlets from your code.

    <html:select styleId="colorCodeId" property="msSpec.colorcodeId" name="Form"  styleClass="form-control" style="${test1}">
                                <option value="-1"></option>
                                <html:optionsCollection property="colorcodeList" />
                            </html:select> 
    

    In the action you write

    List<LabelValueBean> colorcodeList = new ArrayList<LabelValueBean>();
    for (Mty property : customPropertyList) {
                LabelValueBean bean = new LabelValueBean(property.getName(), property.getId().toString());
    
    if (property instanceof ColorCode) {
                    test1 = property.getName();
                    System.out.println("test1: " + test1);
                    request.setAttribute("test1", "background: "+test1+";");
                    colorcodeList.add(bean);
                }
    
    }