没有什么内在的错误,直接使用servlet但两者Spring MVC和引导提供了很多工具,使您的生活更轻松,让你的代码更简洁。我会为您提供一些需要深入研究的领域,但请参阅GitHub上的更多示例以供进一步阅读。当你翻翻文档,请仔细看@ModelAttribute
,th:object
和@RequestParam
。
假设您的foo.html:
<form th:action="@{/foo}" th:object="${someBean}" method="post">
<input type="text" id="datePlanted" name="datePlanted" />
<button type="submit">Add</button>
</form>
窗体使用Thymeleaf的th:object
符号,我们可以参考使用Spring的ModelAttribute
方法的参数。
那么你的控制器可以有:
@Controller
public class MyController {
@GetMapping("/foo")
public String showPage(Model model) {
model.addAttribute("someBean", new SomeBean()); //assume SomeBean has a property called datePlanted
return "foo";
}
@PostMapping("/foo")
public String showPage(@ModelAttribute("someBean") SomeBean bean) {
System.out.println("Date planted: " + bean.getDatePlanted()); //in reality, you'd use a logger instead :)
return "redirect:someOtherPage";
}
}
注意,在上面的控制器,我们没有必要扩展任何其他类。只需注释并设置即可。
如果你正在寻找打印在Java代码名为myParam
的URL参数的值,春天让你在与你@RequestParam
控制器做到这一点很容易的。它甚至可以将其转换之类的东西Integer
类型无需任何额外的工作就在你身边:
@PostMapping("/foo")
public String showPage(@ModelAttribute("someBean") SomeBean bean, @RequestParam("myParam") Integer myIntegerParam) {
System.out.println("My param: " + myIntegerParam);
return "redirect:someOtherPage";
}
我还没有包括的步骤处理日期正确,因为这是超出范围对于这个问题我,但你可以看看添加像这样到控制器,如果你遇到的问题:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
}
编辑:SomeBean
是一个POJO:
public class SomeBean {
private LocalDate datePlanted;
//include getter and setter
}
谢谢你,这么德泰引导的解释,我使用Spring Boot目前我还没有创建或遇到任何bean。我能做些什么来创建一个bean?遵循你的方法“someBean”。我必须为此创建一个xml配置文件吗? – Jesse
不,谷歌术语POJO(普通Java对象) – bphilipnyc
我跟着你的逻辑,我收到一条暧昧的处理程序错误。是因为我使用了ModelAndView吗? – Jesse