gpt4 book ai didi

java - Spring MVC Web应用程序-Model的正确使用

转载 作者:行者123 更新时间:2023-12-01 17:27:51 25 4
gpt4 key购买 nike

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

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

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

感谢您的帮助。米兰

最佳答案

通常,您使用模型将数据从 Controller 传递到 View ,并使用 @RequestParam 从 Controller 中提交的表单获取数据。这意味着,您的 POST 方法将如下所示:

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

关于java - Spring MVC Web应用程序-Model的正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com