繁体   English   中英

Spring MVC Web应用程序-正确使用模型

[英]Spring MVC Web Application - proper use of Model

我正在使用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;
    }
}

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

因此,我的问题是:是否可以以某种方式简化此代码?

感谢您的任何帮助。 米兰

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

public String processYear(@RequestParam("year") int year) {
    // Processing
}

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

@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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM