将枚举绑定到jsp中的单选按钮

时间:2014-07-22 18:06:36

标签: jsp spring-mvc enums radio-button spring-tld

我找到了一些关于此的例子和帖子,但无法找到完整的解决方案或示例 我想使用枚举来保存单选按钮的值 请帮忙。

我有一个如下所示的枚举:

public enum MyEnum implements Serializable {
SUNDAY, MONDAY, TUESDAY
}

我在jsp中有一个表单如下:

MyJSP.jsp

<form:form action="" method="post">
    <input type="radio" id="id1" name="name1" value="value1" >
    <input type="radio" id="id2" name="name2" value="value2" >
    <input type="radio" id="id3" name="name3" value="value3" >               
</form:form>

我有一个模型类如下:
MyModel.java

public class MyModel {
    private String temp;
    private MyEnum myEnum;
    //getters and setters here
}

我有一个控制器如下:
MyController.java

@Controller
@SessionAttributes(MyModel)
public class MyController {

  @ModelAttribute(MyModel)
  public MyModel initMyModel(final HttpServletRequest httpRequest, final HttpSession session) {
    MyModel myModel = new MyModel(.....);
    //code goes here

    return myModel;
  }

  @RequestMapping(value = , method = RequestMethod.GET)
  public String initialViewMyModel(final HttpServletRequest httpRequest, final HttpSession session) {
    return MyJsp;
  }

  @SuppressWarnings("boxing")
  @RequestMapping(value = , method = RequestMethod.POST)
  public String onSubmit(final @ModelAttribute(MyModel) MyModel myModel, final BindingResult bindingResult, final HttpServletRequest httpRequest, final ModelMap modelMap) {
    HttpSession session = httpRequest.getSession();
    //Here is the issue
    MyEnum[] myEnum= myModel.getmyEnum();   //I want here to get the index or anything so that I could identify the selected radio button and use the switch case further but getting null here
    switch (//----) {
        case SUNDAY :
            break;

        case MONDAY :
            break;

        case TUESDAY :
            break;
    }

    return "someotherJSP";
  }

如何将MyJsp.jsp中的单选按钮绑定到枚举值,以便根据所选的单选按钮获取枚举值?
简单的单选按钮或弹簧:无线电标签可以为我工作 请帮忙!

1 个答案:

答案 0 :(得分:0)

表示单个操作的单选按钮必须具有相同的name。从以下开始:

<form:form action="" method="post">
  <input type="radio" name="day" value="SUNDAY" >
  <input type="radio" name="day" value="MONDAY" >
  <input type="radio" name="day" value="TUESDAY" >               
</form:form>

然后,只需收集控制器中的单选按钮值:

@RequestMapping
public String onSubmit(@RequestParam MyEnum day)
{
  ...
}

如果用户选择了其中一个单选按钮值,您将能够在映射的控制器方法中读取该值。您还可以在模型对象内的字段中收集选定的值,例如:

@RequestMapping
public String onSubmit(FormModel model)
{
  ...
}

其中FormModel是一个包含名为day的字段的Java类。