基础框架 SpringMVC请求参数绑定
一、绑定机制
1. 表单提交的数据都是k=v格式的 username=haha&password=1232. SpringMVC的参数绑定过程是把表单提交的请求参数,作为控制器中方法的参数进行绑定的3. 要求:提交表单的name和参数的名称是相同的
二、支持数据类型
1. 基本数据类型和字符串类型2. 实体类型(JavaBean)3. 集合数据类型(List、map集合等)
三、基本数据类型和字符串类型
1. 提交表单的name和参数的名称是相同的2. 区分大小写
四、实体类型(JavaBean)
1. 提交表单的name和JavaBean中的属性名称需要一致2. 如果一个JavaBean类中包含其他的引用类型,那么表单的name属性需要编写成:对象.属性 例如:address.name
五、集合类型(list,map)
1. JSP页面编写方式:list[0].属性
六、自定义类型转换器
Springmvc本身已经做了很多类型转换器,因为所有传过来的参数都是字符串类型,所有常用的都已经转换,包括日期类型,但是日期类型只支持“yyyy/MM/DD”,不支持“yyyy-MM-DD”类型,所以这种情况以及其他没有转换的特殊情况可以自定义类型转换器。
七、案例验证
目录结构
引入依赖
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hello</groupId> <artifactId>springmvc_demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc_demo Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>springmvc_day01_01_start</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build></project>
定义web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app> <display-name>Archetype Created Web Application</display-name> <!--配置解决中文乱码的过滤器--> <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> <!--配置前端控制器--> <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:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>
定义springmvc.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.hello"/> <!-- 视图解析器对象 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--配置自定义类型转换器--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.hello.convert.StringToDateConverter"/> </set> </property> </bean> <!-- 开启SpringMVC框架注解的支持 --> <mvc:annotation-driven conversion-service="conversionService"/> <!--<mvc:annotation-driven/>--></beans>
创建Controller,实体类,转换器等对象
/** * @author zrj * @date 2021/1/1 * @since V1.0 **/public class Account implements Serializable {private String username; private String password; private Double money; /** * 引用类型 */ private User user; private List<User> list; private Map<String, User> map; public Account() {} public Account(String username, String password, Double money, User user, List<User> list, Map<String, User> map) {this.username = username; this.password = password; this.money = money; this.user = user; this.list = list; this.map = map; } public String getUsername() {return username; } public void setUsername(String username) {this.username = username; } public String getPassword() {return password; } public void setPassword(String password) {this.password = password; } public Double getMoney() {return money; } public void setMoney(Double money) {this.money = money; } public User getUser() {return user; } public void setUser(User user) {this.user = user; } public List<User> getList() {return list; } public void setList(List<User> list) {this.list = list; } public Map<String, User> getMap() {return map; } public void setMap(Map<String, User> map) {this.map = map; } @Override public String toString() {return "Account{" "username='" username '\'' ", password='" password '\'' ", money=" money ", user=" user ", list=" list ", map=" map '}'; }}
/** * @author zrj * @date 2021/1/1 * @since V1.0 **/public class User implements Serializable{private String uname; private Integer age; private Date date; public String getUname() {return uname; } public void setUname(String uname) {this.uname = uname; } public Integer getAge() {return age; } public void setAge(Integer age) {this.age = age; } public Date getDate() {return date; } public void setDate(Date date) {this.date = date; } @Override public String toString() {return "User{" "uname='" uname '\'' ", age=" age ", date=" date '}'; }}
/** * 转换器 * 字符串转日期类型yyyy-MM-dd * * @author zrj * @date 2021/1/1 * @since V1.0 **/public class StringToDateConverter implements Converter<String, Date> {@Override public Date convert(String source) {// 判断 if (source == null) {throw new RuntimeException( "请您传入数据" ); } // 格式化字符串 DateFormat df = new SimpleDateFormat( "yyyy-MM-dd" ); try {// 把字符串转换日期 return df.parse( source ); } catch (Exception e) {throw new RuntimeException( "数据类型转换出现错误" ); } }}
/** * 请求参数绑定 * * @author zrj * @date 2021/1/1 * @since V1.0 **/@Controller@RequestMapping("/param")public class ParamController {/** * 请求参数绑定测试 * 绑定字符串 * * @return */ @RequestMapping("/requestParamTest") public String requestParamTesst(String username, String password) {System.out.println( "请求参数绑定测试-绑定字符串" ); System.out.println( "用户名:" username ",密码:" password ); return "success"; } /** * 请求参数绑定测试 * 绑定bean对象 * * @return */ @RequestMapping("/requestBeanTest") public String requestBeanTest(Account account) {System.out.println( "请求参数绑定测试-绑定bean对象" ); System.out.println( "请求参数:" account ); return "success"; } /** * 自定义类型转换器 * data日期类型支持格式:2020/01/09,不支持格式:2020-01-09 * 所以需要自定义类型转换器 * * @param user * @return */ @RequestMapping("/saveUser") public String saveUser(User user) {System.out.println( "自定义类型转换器执行了..." ); System.out.println( "请求参数:" user ); return "success"; } /** * 原生的API * * @return */ @RequestMapping("/testServlet") public String testServlet(HttpServletRequest request, HttpServletResponse response) {System.out.println( "原生的API执行了..." ); System.out.println( request ); HttpSession session = request.getSession(); System.out.println( session ); ServletContext servletContext = session.getServletContext(); System.out.println( servletContext ); System.out.println( response ); return "success"; }}
创建页面jsp
param.jsp
<%-- Created by IntelliJ IDEA. User: zrj Date: 2021/1/1 Time: 14:56 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>请求参数绑定测试</title></head><body> <%-- 请求参数绑定测试-绑定字符串 --%> <span>请求参数绑定测试-绑定字符串</span><br/> <a href="param/requestParamTest?username=hello&password=123">请求参数绑定</a><br/> <%-- 请求参数绑定测试-绑定bean对象 --%> <span>请求参数绑定测试-绑定bean对象</span> <form action="param/requestBeanTest" method="post"> 姓名:<input type="text" name="username" /><br/> 密码:<input type="text" name="password" /><br/> 金额:<input type="text" name="money" /><br/> 用户姓名:<input type="text" name="user.uname"/><br/> 用户年龄:<input type="text" name="user.age"/><br/> <input type="submit" value="提交" /><br/> </form> <%--把数据封装Account类中,类中存在list和map的集合 --%> <span>请求参数绑定测试-绑定类中存在list和map的集合</span> <form action="param/saveAccount" method="post"> 姓名:<input type="text" name="username"/><br/> 密码:<input type="text" name="password"/><br/> 金额:<input type="text" name="money"/><br/> list用户姓名:<input type="text" name="list[0].uname"/><br/> list用户年龄:<input type="text" name="list[0].age"/><br/> map用户姓名:<input type="text" name="map['one'].uname"/><br/> map用户年龄:<input type="text" name="map['one'].age"/><br/> <input type="submit" value="提交"/><br/> </form> <%--自定义类型转换器 --%> <span>请求参数绑定测试-自定义类型转换器</span> <form action="param/saveUser" method="post"> 用户姓名:<input type="text" name="uname" /><br/> 用户年龄:<input type="text" name="age" /><br/> 用户生日:<input type="text" name="date" /><br/> <input type="submit" value="提交" /><br/> </form> <span>请求参数绑定测试-Servlet原生的API</span> <a href="param/testServlet">Servlet原生的API</a></body></html>
赞 (0)