jet*_*ett 3 spring-mvc thymeleaf
我是Spring MVC的新手(来自Grails).是否可以使用HashMap作为表单支持bean?
在Grails中,可以从任何控制器操作访问一个名为params的对象.Params只是一个包含POSTed数据中包含的所有字段值的映射.从我到目前为止所读到的,我必须为我的所有表单创建一个表单支持bean.
是否可以使用Maps作为支持对象?
您不需要使用表单支持对象.如果您只想访问请求中传递的参数(例如POST,GET ......),您需要使用HttpServletRequest#getParameterMap方法获取参数map .查看将所有参数名称和值打印到控制台的示例示例.
另一方面.如果要使用绑定,可以将Map对象包装到表单支持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:/";
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1340 次 |
| 最近记录: |