一、单个数据提交数据
jsp代码:
<h2>1单个数据提交</h2>
<form action="${pageContext.request.contextPath}/one.action">
name<input name="myname"/><br>
age<input name="age">
<input type="submit" value="提交">
</form>
测试代码:
@Controller
public class DataSubmitAction {
@RequestMapping("/one.action")
public String one(String myname, int age) {
System.out.println("myname=" + myname + ",age=" + (age + 10));
return "main";
}
二、对象封装提交数据
【注】需要保证请求参数的名称与实体类中成员变量名称一致
jsp代码:
<h2>2对象数据封装数据提交</h2>
<form action="${pageContext.request.contextPath}/two.action">
name<input name="name"/><br>
age<input name="age"><br>
<input type="submit" value="提交">
</form>
测试代码:
@RequestMapping("/two.action")
public String two(User user) {
System.out.println(user);
return "main";
}
三、动态占位符提交数据
【注】只能用于超链接或地址提交数据,使用注解来解析
jsp代码:
<h2>3.动态占位符提交</h2>
<a href="${pageContext.request.contextPath}/three/张三/20.avction">动态提交</a>
测试代码:
@RequestMapping("/three/{name}/{age}.action")
public String three(@PathVariable String name, @PathVariable int age) {
System.out.println("myname=" + name + ",age=" + (age + 10));
return "main";
}
四、映射名称不一致的时候如何提交数据
【注】提交请求参数与action方法的形参的名称不一致,使用注解@RequestParam来解析
jsp代码:
<h2>4.参数名称不一致解决方案</h2>
<form action="${pageContext.request.contextPath}/four.action" method="post">
name<input name="name"/><br>
age<input name="age"><br>
<input type="submit" value="提交">
</form>
测试代码:
@RequestMapping("/four.action")
public String four(@RequestParam("name") String n, @RequestParam("age") int a) {
System.out.println("myname=" + n + ",age=" + (a + 10));
return "main";
}
五、手工提取数据
jsp代码:
<h2>5手工提取数据</h2>
<form action="${pageContext.request.contextPath}/five.action">
name<input name="name"/><br>
age<input name="age">
<input type="submit" value="提交">
</form>
测试代码:
@RequestMapping("/five.action")
public String five(HttpServletRequest request) {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
System.out.println("myname=" + name + ",age=" + (age + 10));
return "main";
}