客户端请求参数的格式是:name=value&name=value...
服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接受如下类型的参数
• 基本类型参数
• pojo
• 数组类型参数
• 集合类型参数
基本数据类型获取
@RequestMapping(value = "/quick11") @ResponseBody//void表示不进行数据回写, responsebody 表示不尽兴页面跳转,二者不冲突 public void save11(String username,int age)throws Exception{ System.out.println("username = " + username); System.out.println("age = " + age); }//做模拟可以在浏览器搜索框写入localhost:8080/user/quick11?username=zhangsan&age=18pojo类型参数获取
注意controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配。
package com.Itheima.domain; public class User { String name; int age; public User() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String name, int age) { this.name = name; this.age = age; } }@RequestMapping(value = "/quick12") @ResponseBody//pojo对象 domain包下的user对象 public void save11(User user)throws Exception{ System.out.println("user = " + user); }//做模拟可以在浏览器搜索框写入localhost:8080/user/quick11?username=zhangsan&age=18数组类型参数的获取
Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/user/quick12?strs=111&strs=222&strs=333
@RequestMapping(value = "/quick13") @ResponseBody public void quickMethod11(String[] strs)throws Exception{ System.out.println(Arrays.asList(strs));//数组打印都是地址,转换成集合打印会清晰很多 }//做模拟可以在浏览器搜索框写入localhost:8080/user/quick13?strs=aaa&strs=bbb&strs=ccc集合类型的参数获取
情景一(常见):
获得集合参数的时候,需要将集合参数包装到pojo中才可以
package com.Itheima.domain; public class User { String name; int age; public User() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String name, int age) { this.name = name; this.age = age; } }package com.Itheima.domain; import java.util.List; public class VO { private List<User> userList; public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) {} @Override public String toString() { return super.toString(); } }@RequestMapping(value = "/quick14") @ResponseBody public void quickMethod14(VO vo) throws Exception { System.out.println("vo = " + vo); }<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="{pageContext.request.contextPath}/user/quick14" method="post"> <%-- 表明是第一个对象的name 或者age--%> <input type="text" name="userList[0].name"><br/> <input type="text" name="userList[0].age"><br/> <input type="text" name="userList[1].name"><br/> <input type="text" name="userList[1].age"><br/> <input type="submit" value="提交"> </form> </body> </html>情景二:
当使用Ajax提交时,可以指定contentType为json形式,那么在方法参数位置使用@RequestBody可以直接接受集合数据而无需使用pojo进行包装
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <script src="${pageContext.request.contextPath}/js/jquery.min.js"></script> <script> let userList = new Array(); userList.push({name:"zhangsan",age:14}); userList.push({name:"lisi",age:18}); $.post({ url:"${pageContext.request.contextPath}/user/quick15", data:JSON.stringify(userList), contentType:"application/json;charset=utf-8" }) </script> </body> </html>@RequestMapping(value = "/quick16") @ResponseBody public void quickMethod16(@RequestBody List<User> userList) throws Exception { System.out.println(userList); }因涉及静态资源访问权限,必须在spring-mvc.xml添加
<!-- 开放资源的访问,一般是静态资源 前面是到什么地方寻找 后面是寻找的位置--> <mvc:resources mapping="/js/**" location="/js/"/> <mvc:resources mapping="/img/**" location="/img/"/> <!-- 第二种方式 如果SpringMVC找不到对应的资源就转让原始的容器(这里是tomcat)来找--> <mvc:default-servlet-handler/>防止乱码的解决方案——全局过滤
<!-- 配置全局过滤的fliter 防止出现乱码情况--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>编码过滤器必须是 web.xml 第一个过滤器!如果你在它前面放了其他 Filter、比如登录拦截、权限过滤器,请求参数已经被读取解析过了,再设置编码就晚了,中文依然乱码。
参数绑定RequestParam
解决一个问题,如果提交的参数和封装的参数不一致名字写错了例如name写成了username这种,加上可以识别
获取restful风格参数
restful是一种架构风格、设计风格,不是标准,只提供一套设计原则和约束条件,主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更加简洁,更富有层次,更易于实现缓存机制。
restful风格的请求是使用:url=+请求方式,表示一次请求目的,HTTP协议里面四个表示操作方式的动词如下:
GET:用于获取资源
POST:用于新建资源
PUT:用于更新资源
DELETE:用于删除资源
自定义类型转换器
package com.Itheima.converter; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateConverter implements Converter<String, Date> { public Date convert(String dateString) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//示例:输入2020-01-01 Date date = null; try { date = sdf.parse(dateString); } catch (Exception e) { throw new RuntimeException(e); } return date; } }<!-- 声明转换器--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.Itheima.converter.DateConverter"></bean> </list> </property> </bean> <mvc:annotation-driven conversion-service="conversionService"/>@RequestMapping(value = "/quick17") @ResponseBody public void save17(Date date) throws Exception { System.out.println(date); }获取Servlet相关API
获取请求头
HTTP请求跑出请求内容(请求体)外还存在请求头和请求行、空行(用来隔开请求头和请求体)
文件上传
注意 enctype仅对Post方法生效,例如,GET方法不存在请求体
当form表单修改为多部分表单时,即enctype="multipart/form-data"的形式
request.getParameter()方法将失效。 原因,本质上是获取url中 什么&什么 这样形式的内容。
单文件上传步骤:
1. 导入FileUpload和IO坐标
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency>2. 配置文件上传解析器
<!-- 配置文件上传解析器--> <bean id="MultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- //上传文件的编码类型--> <property name="defaultEncoding" value="UTF-8"/> <!-- 上传文件的总大小--> <property name="maxUploadSize" value="50000"/> <!-- 上传单个文件的大小--> <property name="maxUploadSizePerFile" value="50000"/> </bean>3. 编写文件上传代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype=""> 姓名: <input type="text" name="name"> 请选择文件:<input type="file" name="uploadFile"> <input type="submit" value="提交"> </form> </body> </html>@RequestMapping(value = "/quick19") @ResponseBody public void quickMethod19(String name, MultipartFile uploadFile) throws Exception { System.out.println("name = " + name); System.out.println("uploadFile = " + uploadFile); // 获得上传文件的名称 String originalFilename = uploadFile.getOriginalFilename(); uploadFile.transferTo(new File("F:\\upload\\"+uploadFile.getOriginalFilename())); }多文件上传
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype=""> 姓名: <input type="text" name="name"> 请选择文件:<input type="file" name="uploadFile"> 请选择需要上传的第二个文件:<input type="file" name="uploadFile2"> <input type="submit" value="提交"> </form> </body> </html>@RequestMapping(value = "/quick19") @ResponseBody public void quickMethod19(String name, MultipartFile uploadFile,MultipartFile uploadFile2) throws Exception { System.out.println("name = " + name); System.out.println("uploadFile = " + uploadFile); // 获得上传文件的名称 String originalFilename = uploadFile.getOriginalFilename(); String originalFilename2 = uploadFile2.getOriginalFilename(); uploadFile.transferTo(new File("F:\\upload\\"+uploadFile.getOriginalFilename())); uploadFile2.transferTo(new File("F:\\upload\\"+uploadFile2.getOriginalFilename())); }@RequestMapping(value = "/quick19") @ResponseBody public void quickMethod19(String name, MultipartFile[] uploadFile) throws Exception { System.out.println("name = " + name); System.out.println("uploadFile = " + uploadFile); for(MultipartFile multipartFile : uploadFile) { // 获得上传文件的名称 String originalFilename = multipartFile.getOriginalFilename(); multipartFile.transferTo(new File("F:\\upload\\"+originalFilename)); } }