如何映射弹簧形式的字节:选择?

时间:2013-04-08 13:50:42

标签: java spring

在我的模型中,我有变量 字节低= 0; 字节高= 1;

现在低和高可以映射到字符串O1,O2,O3中的3个值;

例如,如果low = 0,它可以映射到O1,如果为1,它将映射到O2。 对于高也是如此。

我应该如何设计我的控制器以通过JSP页面操作这些值。

我有O1,O2,O3的枚举

enum MyEnum {
 O1(0),O2(1),O3(2) so on...
}

我希望使用form:options的下拉列表,这些选项将显示低和高的三个枚举选项。

这里唯一的问题是我已阅读How do I set the selected value in a Spring MVC form:select from the controller?但我无法弄清楚我的字节值将如何创建地图。我想填充这些值。

1 个答案:

答案 0 :(得分:0)

首先,我认为您应该在模型中使用枚举而不是字节。您始终可以从枚举中获取字节值。还要向模型类添加方法,以返回枚举的字节值或字符串值。然后将此字符串值用于您的选择输入框。

你的枚举(我的假设):

public enum MyEnum {
    O1 (0),
    O2 (1),
    O3 (2);

    private final Byte byteVal;       

    private MyEnum(Byte val) {
        byteVal = val;
    }

    public Byte getByteVal(){
        return byteVal;
    }

}

你的模特(我的假设):

public class MyModel{
    MyEnum high; //instead of Byte high
    MyEnum low;//instead of Bye low
    ....
    //This method would return byte to be compatible with your backend as it is right now
    public Byte getHigh(){
        return this.high.getByteVal();
    }
    //This method would allow you to use the string representation for your front end
    public Byte getHighString(){
        return this.high.name();
    }
}

现在在你的选择框的jsp中使用model.highString而不是model.high。

希望这有帮助。