SpringMVC參數綁定/自定義類型轉換器
項目結構
配置文件
-
pom.xml
<?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.xiaoge</groupId> <artifactId>springmvc_bind_conversion</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc_bind_conversion 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.7</maven.compiler.source> <maven.compiler.target>1.7</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_bind_conversion</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.1.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.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</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> <!-- 前端控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定加載的配置文件 ,通過參數contextConfigLocation加載--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> <!-- 當啓動服務器的時候創建servlet對象 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <!-- 前端控制器 --> <servlet-name>dispatcherServlet</servlet-name> <!-- 這裏是/ 攔截所有的請求 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置解決中文亂碼的過濾器 --> <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-app>
-
spring.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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://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.xiaoge"></context:component-scan> <!-- 視圖解析器對象 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 指定控制器對象返回的jsp名稱, 去哪個目錄下尋找 --> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置自定義類型轉換器, 不會覆蓋SpringMVC自帶的類型轉換器, 所以放心配置 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.xiaoge.utils.StringToDateConverter"/> </set> </property> </bean> <!--開啓springMVC框架註解的支持,增加類型轉換器,使其生效--> <mvc:annotation-driven conversion-service="conversionService"/> </beans>
實體類
-
Account
package com.xiaoge.domain; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author xiaoge * @version 1.0 * @date 2020/4/15 14:35 * @detail 賬戶實體類 */ 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 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; }*/ /* @Override public String toString() { return "Account{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", money=" + money + ", 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 + ", list=" + list + ", map=" + map + '}'; } }
-
User
package com.xiaoge.domain; import java.io.Serializable; import java.util.Date; /** * @author xiaoge * @version 1.0 * @date 2020/4/15 19:20 * @detail 用戶實體類 */ 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 + '}'; } }
工具類
-
StringToDateConverter**(重點: 要實現類型轉換必須實現Converte接口中的轉換方法)**
package com.xiaoge.utils; import org.springframework.core.convert.converter.Converter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * @author xiaoge * @version 1.0 * @date 2020/4/15 20:02 * @detail 把字符串轉換成日期 * * Converter<String, Date> String類型轉換成Date類型 * 注意: 這裏的泛型, 是你來設置的, 你想什麼類型轉換成什麼類型, 泛型就怎麼寫 * */ public class StringToDateConverter implements Converter<String, Date> { /** * String source 傳入進來字符串 * @param source * @return */ @Override public Date convert(String source) { // 判斷 if (source == null || "".equals(source)) { throw new RuntimeException("date is null"); } else { // 設置字符串格式 DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { // 將字符串轉換成日期 return df.parse(source); } catch (Exception e) { throw new RuntimeException("data type converter error"); } } } }
控制器
-
ParamController
package com.xiaoge.controller; import com.xiaoge.domain.Account; import com.xiaoge.domain.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author xiaoge * @version 1.0 * @date 2020/4/15 14:20 * @detail 請求參數綁定 */ @Controller @RequestMapping("/param") public class ParamController { /** * 請求參數綁定入門 * @param username * @param password * @return */ @RequestMapping("/paramBind") public String testParamBind(String username, String password) { System.out.println("用戶名: " + username); System.out.println("密碼: " + password); return "success"; } /** * 請求參數綁定數據封裝到JavaBean的類中 * @param account * @return */ @RequestMapping(value = {"saveAccount"}, method = {RequestMethod.POST}) public String saveAccount(Account account) { System.out.println(account); return "success"; } /** * 自動以類型轉換器 * @param user * @return */ @RequestMapping(value = {"saveUser"}, method = {RequestMethod.POST}) public String saveUser(User user) { System.out.println(user); return "success"; } /** * 原生的API * * 需要servletAPI中那個對象 就把那個對象做爲testServlet的參數 * @return */ @RequestMapping(value = {"testServlet"}) public String testServlet(HttpServletRequest request, HttpServletResponse response) { System.out.println(request); System.out.println(request.getSession()); // 獲取session的值 不是 request.getServletContext被搞混系 System.out.println(request.getSession().getServletContext()); System.out.println(response); return "success"; } }
前臺頁面
-
index.jsp
<%-- Created by IntelliJ IDEA. User: xiaoge Date: 2020/4/19 Time: 下午2:13 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>請求參數綁定</title> </head> <body> <%-- 請求參數綁定 --%> <%-- <a href="param/paramBind?username=張三&password=123456">請求參數綁定</a>--%> <%-- 把數據封裝Account類中 <form action="param/saveAccount" method="post"> username: <input type="text" name="username"> <br /> password: <input type="password" name="password"> <br /> money: <input type="text" name="money"> <br /> uname: <input type="text" name="user.uname"> <br /> age: <input type="text" name="user.age"> <br /> <input type="submit" value="提交"> </form> --%> <%-- 把數據封裝Account類中, 類中存在list和map集合 <form action="param/saveAccount" method="post"> username: <input type="text" name="username"> <br /> password: <input type="password" name="password"> <br /> money: <input type="text" name="money"> <br /> <%– 把uname和age封裝成一個user對象, 把這個user對象存儲到List集合的0號位置 –%> uname: <input type="text" name="list[0].uname"> <br /> age: <input type="text" name="list[0].age"> <br /> <%– 把uname和age封裝成一個user對象, 把這個user對象存儲到map集合的key爲one的值的位置 –%> uname: <input type="text" name="map['one'].uname"> <br /> age: <input type="text" name="map['one'].age"> <br /> <input type="submit" value="提交"> </form>--%> <%-- <form action="param/saveUser" method="post"> uname: <input type="text" name="uname"> <br /> age: <input type="password" name="age"> <br /> date: <input type="text" name="date"> <br /> <input type="submit" value="提交"> </form>--%> <a href="param/testServlet">Servlet原生API</a> </body> </html>
-
success.jsp
<%-- Created by IntelliJ IDEA. User: xiaoge Date: 2020/4/19 Time: 下午2:13 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>success</title> </head> <body> <h3>成功</h3> </body> </html>