沒有什麼內在的錯誤,直接使用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