springmvc五种数据提交方式
1、单个提交数据
页面:
<form action="${pageContext.request.contextPath}/one.action"> 姓名:<input name="myname"><br> 年龄:<input name="age"><br> <input type="submit" value="提交"> </form>
action类
@RequestMapping("/one") public String one(String myname,int age){ ===>自动注入,并且类型转换 System.out.println("myname="+myname+",age="+(age+100)); return "main"; }
2、对象封装提交数据
在提交请求中,保证请求参数的名称与实体类中成员变量的名称一致,则可以自动创建对象,则可以自动提交数据,自动类型转换,自动封装数据到对象中.
实体类:
public class Users { private String name; private int age;}
页面:
<form action="${pageContext.request.contextPath}/two.action" method="post"> 姓名:<input name="name"><br> 年龄:<input name="age"><br> <input type="submit" value="提交"> </form>
action:
@RequestMapping("/two") public String two(Users u){ System.out.println(u); return "main"; }
3、动态占位符提交
仅限于超链接或地址拦提交数据.它是一杠一值,一杠一大括号,使用注解@PathVariable来解析.
页面:
<a href="${pageContext.request.contextPath}/three/张三/22.action">动态提交</a>
action:
@RequestMapping("/three/{uname}/{uage}") public String three( @PathVariable("uname") ===>用来解析路径中的请求参数 String name, @PathVariable("uage") int age){ System.out.println("name="+name+",age="+(age+100)); return "main"; }
4、映射名称不一致
提交请求参数与action方法的形参的名称不一致,使用注解@RequestParam来解析
页面:
<form action="${pageContext.request.contextPath}/four.action"> <input name="name"> <input name="age"> <input type="submit" value="提交"/> </form>
action:
@RequestMapping("/four") public String four( @RequestParam("name") String uname, @RequestParam("age")int uage){ System.out.println("uname=" + uname + ",uage=" + (uage+100)); return "main"; }
5、手工提取数据
页面:
<form action="${pageContext.request.contextPath}/five.action"> <input name="name"> <input name="age"> <input type="submit" value="提交"/> </form>
action:
@RequestMapping("/five") public String five(HttpServletRequest request){ String uname = request.getParameter("name"); Integer uage = Integer.parseInt(request.getParameter("age")); System.out.println("uname=" + uname + ",uage=" + (uage+100)); return "main"; }
补充:中文乱码解决方案
web.xml文件中配置过滤器.
<filter> <filter-name>encode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 配置参数 private String encoding; private boolean forceRequestEncoding; private boolean forceResponseEncoding; --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>