[英]Alternative of @ModelAttribute annotation in Spring
就像在Spring
一樣,我們有httpServeletRequest.getParameter("key")
作為@RequestParam("key")
替代品,我們有任何替代品@ModelAttribute("key")
嗎?
model.addAttribute("student",new Student());
...
...
@RequestMapping("/processStudentForm")
public String processTheForm(
@ModelAttribute("student") Student student
)
{
...
}
我們有類似的東西嗎?
public String processTheForm(
Model model
)
{
Student student = model.getAtribute("key");
...
}
更新 1
@RequestMapping("/showStudentForm")
public String showTheForm(Model model) {
model.addAttribute("key",new Student());
return "studentForm";
}
<form:form action='processStudentForm' modelAttribute='key' method='post'>
...
</form:form>
我將表單值綁定到學生對象中。 如何通過請求對象訪問這個模型屬性??
學生模型對象不能通過請求對象直接訪問,但您可以通過與請求對象不同的方式訪問它。默認情況下,spring 在后台做了很多工作,它使用 FormHttpMessageConverter 將其轉換為應用程序/x 上的模型映射-www-form-urlencoded 請求您可以參考文檔。
你可以像 spring 在內部做的一樣。我試過這個它的工作,但你可以用多種方式來做,請參閱堆棧溢出帖子以獲取其他答案
Map map = httpServletRequest.getParameterMap().entrySet()
.stream().collect(Collectors.toMap(e -> e.getKey(), e -> Arrays.stream(e.getValue()).findFirst().get()));
Student student = new ObjectMapper().convertValue(map, Student.class);
從 Java servlet 中的 POST 請求獲取請求負載
但使用默認實現始終是一個好習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.