There's nothing inherently wrong with using servlets directly but both Spring MVC and Boot offer many tools to make your life easier and make your code more concise. I'll provide you with some areas to delve into, but do take a look at more examples on GitHub for further reading. When you're looking through the docs, take a close look at @ModelAttribute
, th:object
, and @RequestParam
.
Let's you have foo.html:
<form th:action="@{/foo}" th:object="${someBean}" method="post">
<input type="text" id="datePlanted" name="datePlanted" />
<button type="submit">Add</button>
</form>
The form uses Thymeleaf's th:object
notation which we can refer to using Spring's ModelAttribute
method parameter.
Then your Controller could have:
@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";
}
}
Note that in the above controller, we didn't need to extend any other class. Just annotate and you're set.
If you're looking to print the value of a URL parameter named myParam
in your Java code, Spring let's you do this easily in your controller with @RequestParam
. It can even convert it to things like Integer
types without any extra work on your side:
@PostMapping("/foo")
public String showPage(@ModelAttribute("someBean") SomeBean bean, @RequestParam("myParam") Integer myIntegerParam) {
System.out.println("My param: " + myIntegerParam);
return "redirect:someOtherPage";
}
I'm also not including the steps to handle dates appropriately since that is out of scope for this question, but you can look at adding something like this to your controller if you come across issues:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
}
Edit: SomeBean
is a POJO:
public class SomeBean {
private LocalDate datePlanted;
//include getter and setter
}