2014-10-09 66 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

相关问题