2

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

我有一个像下面这样的枚举:

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 中的单选按钮绑定到枚举值,以便根据所选单选按钮获取枚举值?
简单的单选按钮或 spring:radio 标签都可以为我工作。
请帮忙 !

4

1 回答 1

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是一个 Java 类,其中包含一个名为day.

于 2014-07-23T02:09:47.103 回答