SpringMVC18_SpringMVC获得请求数据5
一、获得请求参数-请求参数类型
客户端请求参数的格式是: name=value&name=value......
服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数:
- 基本类型参数
- POJO类型参数:简单java bean
- 数组类型参数
- 集合类型参数
二、获得请求参数-获得基本类型参数
Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配。并且能自动做类型转换;
自动的类型转换是指从String向其他类型的转换
http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12
这表示Controller的业务方法中有两个参数-形参:username和age。
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick11") @ResponseBody public void save11(String username,int age) { System.out.println(username); System.out.println(age); } }
浏览器访问localhost:8080/user/quick11?username=zhangsan&age=18,检查控制台结果:
三、获得请求参数-获得POJO类型参数
Controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配。
package com.itheima.domain; public class User { private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", age=" + age + '}'; } }
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick12") @ResponseBody public void save12(User user) { System.out.println(user); } }
浏览器访问localhost:8080/user/quick12?username=lisi&age=20,检查控制台结果:
浏览器访问localhost:8080/user/quick12?username=lisi,检查控制台结果:
四、获得请求参数-获得数组类型参数
Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配。
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick13") @ResponseBody public void save13(String[] strs) { System.out.println(Arrays.asList(strs)); }
浏览器访问http://localhost:8080/user/quick13?strs=aaa&strs=bbb&strs=ccc,检查控制台结果:
五、获得请求参数-获得集合类型参数1
获得集合参数时,要将集合参数包装到一个POJO中才可以。
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) { this.userList = userList; } @Override public String toString() { return "VO{" + "userList=" + userList + '}'; } }
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick14") @ResponseBody public void save14(VO vo) { System.out.println(vo); } }
浏览器访问http://localhost:8080/form.jsp,检查浏览器显示,并输入对应的值提交
提交后检查控制台输出:
六、获得请求参数-获得集合类型参数2
当使用ajax提交时,可以指定contentType为json形式,那么在方法参数位置使用@RequestBody可以直接接收集合数据而无需使用POJO进行包装。
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick15") @ResponseBody public void save15(@RequestBody List<User> userList) { System.out.println(userList); } }
拷贝jquery-3.3.1.js文件到webapp/js目录下,并在webapp目录下新建ajax.jsp
浏览器访问http://localhost:8080/ajax.jsp,观察浏览器控制台报错:
解决办法:编辑spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Controller的组件扫描--> <!--如果配置com.itheima则和spring扫重复了--> <context:component-scan base-package="com.itheima.controller"/> <!--配置内部资源视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- /jsp/success.jsp --> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- mvc的注解驱动 --> <mvc:annotation-driven />
<!-- 开放静态资源,mapping是访问服务端找资源的地址,location是具体资源的目录 --> <mvc:resources mapping="/js/**" location="/js/" /> </beans>
再次浏览器访问http://localhost:8080/ajax.jsp,观察浏览器控制台不报错了,检查tomcat控制台结果:
七、获得请求参数-静态资源访问的开启
当有静态资源需要加载时,比如jquery文件,通过谷歌开发者工具抓包发现,没有加载到jquery文件,原因是SpringMVC的前端控制器DispatcherServlet的url-pattern配置的是/,代表对所有的资源都进行过滤操作,我们可以通过以下两种方式指定放行静态资源:
- 在spring-mvc.xml配置文件中指定放行的资源
mapping是访问服务端匹配的地址如/js/jquery-3.3.1.js,location是具体资源的目录(webapp/js目录)
<mvc:resources mapping="/js/**" location="/js/" />
-
使用<mvc:default-servlet-handler/>标签
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Controller的组件扫描--> <context:component-scan base-package="com.itheima.controller"/> <!--配置内部资源视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- /jsp/success.jsp --> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- mvc的注解驱动 --> <mvc:annotation-driven /> <!-- <mvc:resources mapping="/js/**" location="/js/" />--> <!-- springmvc框架帮你匹配地址,找不到资源,交给原始容器tomcat找静态资源--> <mvc:default-servlet-handler /> </beans>
浏览器访问http://localhost:8080/ajax.jsp,检查tomcat控制台输出List
八、获得请求参数-配置全局乱码过滤器
当post请求时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤。
浏览器访问http://localhost:8080/form.jsp,输入中文username提交时,发现控制台输出乱码:
解决办法:编辑web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 配置全局过滤的filter --> <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> <!--配置SpringMVC的前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!--服务器启动时加载spring创建对象--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--全局初始化参数--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--配置监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.itheima.web.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <!-- 浏览器访问路径 --> <url-pattern>/userServlet</url-pattern> </servlet-mapping> </web-app>
浏览器再次访问http://localhost:8080/form.jsp,输入中文username提交时,检查控制台输出:
九、获得请求参数-参数绑定注解@RequestParam
当请求的参数名称与Controller的业务方法参数名称不一致时,就需要通过@RequestParam注解显示的绑定
注解@RequestParam还有如下参数可以使用:
- value:请求参数名称
- required:此在指定的请求参数是否必须包括,默认是true,提交时如果没有此参数则报错
- defaultValue:当没有指定请求参数时,则使用指定的默认值赋值
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick16") @ResponseBody public void save16(String username) { System.out.println(username); } }
浏览器访问http://localhost:8080/user/quick16?username=zhangsan,观察控制台能正常输出,见下图
浏览器访问http://localhost:8080/user/quick16?name=zhangsan,观察控制台不能正常输出zhangsan,见下图
解决办法:
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick16") @ResponseBody //@RequestParam(value = "name")可以简写成 @RequestParam("name") public void save16(@RequestParam(value = "name") String username) { System.out.println(username); } }
浏览器访问http://localhost:8080/user/quick16?name=zhangsan,观察控制台正常输出zhangsan。这时候就不能访问http://localhost:8080/user/quick16?username=zhangsan了会报错,因为name参数required默认是true。
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick16") @ResponseBody //value不能省略 public void save16(@RequestParam(value = "name",required = false") String username) { System.out.println(username); } }
这时候再访问http://localhost:8080/user/quick16?username=zhangsan就不报错了,tomcat控制台输出:null
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick16") @ResponseBody public void save16(@RequestParam(value = "name",required = false,defaultValue = "wangwu") String username) { System.out.println(username); } }
这时候再访问http://localhost:8080/user/quick16?username=zhangsan,检查tomcat控制台输出:
十、获得请求参数-Restful风格的参数的获取
Restful是一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制等。
Restful风格的请求是使用“url+请求方式”表示一次请求目的的,HTTP 协议里面四个表示操作方式的动词如下:
- GET:用于获取资源
- POST:用于新建资源
- PUT:用于更新资源
- DELETE:用于删除资源
例如:
- /user/1 GET : 得到id = 1 的 user
- /user/1 DELETE: 删除id = 1 的 user
- /user/1 PUT: 更新id = 1 的 user
- /user POST: 新增user
上述url地址/user/1中的1就是要获得的请求参数,在SpringMVC中可以使用占位符进行参数绑定。地址/user/1可以写成/user/{id},占位符{id}对应的就是1的值。
在业务方法中我们可以使用@PathVariable注解进行占位符的匹配获取工作。
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/user") public class UserController { //http://localhost:8080/user/quick19/zhangsan @RequestMapping(value="/quick19/{username}") @ResponseBody public void save19(@PathVariable(value = "username") String username) { System.out.println(username); } }
浏览器访问http://localhost:8080/user/quick19/zhangsan,检查控制台输出:
十一、获得请求参数-自定义类型转换器
- SpringMVC默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成int型进行参数设置。
- 但是不是所有的数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自定义转换器。
自定义类型转换器的开发步骤:
1. 定义转换器类实现Converter接口
2. 在spring-mvc.xml配置文件中声明转换器
3. 在<annotation-driven>中引用转换器
代码实现:
1. 定义转换器类实现Converter接口
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 dateStr) { //将日期字符串转换成日期对象 返回 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = format.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } return date; } }
2. 在spring-mvc.xml配置文件中声明转换器
3. 在<annotation-driven>中引用转换器
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Controller的组件扫描--> <context:component-scan base-package="com.itheima.controller"/> <!--配置内部资源视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- /jsp/success.jsp --> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- mvc的注解驱动 --> <mvc:annotation-driven conversion-service="conversionService"/> <!-- springmvc框架帮你匹配地址,找不到资源,交给原始容器tomcat找静态资源--> <mvc:default-servlet-handler /> <!-- 声明转换器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.itheima.converter.DateConverter"/> </list> </property> </bean> </beans>
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick20") @ResponseBody public void save20(Date date) { System.out.println(date); } }
浏览器访问http://localhost:8080/user/quick20?date=2018-12-21,检查控制台输出:
十二、获得请求参数-获得Servlet相关API
SpringMVC支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:
- HttpServletRequest
- HttpServletResponse
- HttpSession
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick21") @ResponseBody public void save21(HttpServletRequest request, HttpServletResponse response, HttpSession session) { System.out.println(request); System.out.println(response); System.out.println(session); } }
浏览器访问http://localhost:8080/user/quick21,检查控制台输出:
十三、获得请求参数-获得请求头信息
1. 使用@RequestHeader可以获得请求头信息,相当于web阶段学习的request.getHeader(name)
@RequestHeader注解的属性如下:
- value:请求头的名称
- required:是否必须携带此请求头
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick23") @ResponseBody
//浏览器访问地址时,从请求头里找到User-Agent字段的值赋给user_agent public void save23(@RequestHeader(value = "User-Agent",required = false) String user_agent) { System.out.println(user_agent); } }
浏览器访问http://localhost:8080/user/quick23,检查控制台输出:
2. 使用@CookieValue可以获得指定Cookie的值
@CookieValue注解的属性如下:
- value:指定cookie的名称
- required:是否必须携带此cookie
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.domain.User; import com.itheima.domain.VO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/quick24") @ResponseBody public void save24(@CookieValue(value = "JSESSIONID") String jsessionId){ System.out.println(jsessionId); } }
浏览器访问http://localhost:8080/user/quick24,检查控制台输出: