0

我正在使用 Spring Framework 在 Java 中开发 Web 应用程序。在一页上,我让用户选择年份。这是代码:

@Controller
public class MyController {

    @RequestMapping(value = "/pick_year", method = RequestMethod.GET)
    public String pickYear(Model model) {
        model.addAttribute("yearModel", new YearModel);
        return "pick_year";
    }

    @RequestMapping(value = "/open_close_month_list", method = RequestMethod.POST)
    public String processYear(Model model, @ModelAttribute("yearModel") YearModel yearModel) {
        int year = yearModel.getYear();
        // Processing
    }
}


public class YearModel { 
    private int year;

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
}

此实现有效,但我想使用更简单的方法从用户那里获得年份。我认为制作特殊模型只是为了获得一个整数不是很好的方法。

所以,我的问题是:是否有可能以某种方式简化这段代码?

感谢您的任何帮助。米兰

4

2 回答 2

4

通常您使用模型将数据从控制器传递到视图,并用于从控制器中@RequestParam提交的表单中获取数据。意思是,您的 POST 方法如下所示:

public String processYear(@RequestParam("year") int year) {
    // Processing
}
于 2012-11-27T19:51:47.900 回答
1

事实上,你只需要存储整数,你不需要创建一个全新的特殊类来保存它

@Controller
public class MyController {
    @RequestMapping(value = "/pick_year", method = RequestMethod.GET)
    public String pickYear(ModelMap model) {
        model.addAttribute("year", 2012);
        return "pick_year";
    }

    @RequestMapping(value = "/open_close_month_list", method = RequestMethod.POST)
    public String processYear(@ModelAttribute("year") int year) {
        // Processing
    }
}

您可以(如果可能的话)改写您的视图,以便您可以使用@RequestParam将整数直接传递给您的方法pickYear,将其呈现到视图中,以便可以以processYear相同的方式将此参数传递给第二个方法。

@Controller
public class MyController {
    // In the pick_year view hold the model.year in any hidden form so that
    // it can get passed to the process year method
    @RequestMapping(value = "/pick_year", method = RequestMethod.GET)
    public ModelAndView pickYear(@RequestParam("year") int year) {
        ModelAndView model = new ModelAndView("pick_year");
        model.addAttribute("year", 2012);
        return model;
    }

    @RequestMapping(value = "/open_close_month_list", method = RequestMethod.POST)
    public String processYear(@RequestParam("year") int year) {
        // Processing
    }
}
于 2012-11-27T19:53:44.437 回答