2014-10-09 64 views
3

我是Spring MVC(來自Grails)的新手。是否可以使用HashMap作爲表單支持bean?使用HashMap作爲表單支持Bean Spring MVC + ThymeLeaf

在Grails中,可以通過任何控制器操作訪問一個名爲params的對象。 Params只是一個包含POST數據中包含的所有字段值的映射。從我目前閱讀的內容來看,我必須爲我的所有表單創建一個表單支持bean。

是否使用Maps作爲後備對象?

回答

5

您不需要爲此使用表單支持對象。如果您只想訪問在請求中傳遞的參數(例如,POST,GET ...),則需要使用HttpServletRequest#getParameterMap方法獲取參數映射。看一下將所有參數名稱和值輸出到控制檯的示例。

另一方面。如果你想使用綁定,你可以把Map對象包裝成form backing bean。

控制器

import java.util.Arrays; 
import java.util.Map; 
import java.util.Map.Entry; 

import javax.servlet.http.HttpServletRequest; 

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

@Controller 
public class ParameterMapController { 

    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String render() { 
     return "main.html"; 
    } 

    @RequestMapping(value = "/", method = RequestMethod.POST) 
    public String submit(HttpServletRequest req) { 
     Map<String, String[]> parameterMap = req.getParameterMap(); 
     for (Entry<String, String[]> entry : parameterMap.entrySet()) { 
      System.out.println(entry.getKey() + " = " + Arrays.toString(entry.getValue())); 
     } 

     return "redirect:/"; 
    } 
} 

main.html中

<!DOCTYPE html> 
<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
<head> 
    <meta charset="utf-8" /> 
</head> 
<body> 

<form th:action="@{/}" method="post"> 
    <label for="value1">Value 1</label> 
    <input type="text" name="value1" /> 

    <label for="value2">Value 2</label> 
    <input type="text" name="value2" /> 

    <label for="value3">Value 3</label> 
    <input type="text" name="value3" /> 

    <input type="submit" value="submit" /> 
</form> 

</body> 
</html> 
+0

謝謝!這正是我需要的。 – jett 2014-10-14 13:53:57

+0

@ michal.kreuzman你能幫我關於我的問題我不能綁定地圖在jsp 標籤請參閱我的帖子以獲得更詳細的說明http://stackoverflow.com/questions/30679449/forminput-tag-in-jsp -is-不轉換至輸入標籤的的HTML的換地圖屬性 – henrycharles 2015-06-06 07:44:03

相關問題