Spring MVC 自定義數(shù)據(jù)轉(zhuǎn)換器的思路案例詳解
數(shù)據(jù)轉(zhuǎn)換器是指將客戶端 http 請求中的參數(shù)轉(zhuǎn)換為業(yè)務(wù)方法中定義的形參,自定義表示開發(fā)者可以自主設(shè)計轉(zhuǎn)換模式,HandlerAdapter 已經(jīng)提供了通用的轉(zhuǎn)換,比如將 String 轉(zhuǎn)成 int,String 轉(zhuǎn)成 double,表單數(shù)據(jù)的封裝等,但是在特殊的業(yè)務(wù)場景下,HandlerAdapter 無法進(jìn)行轉(zhuǎn)換,就需要開發(fā)者自定義轉(zhuǎn)換器。
我們需要實(shí)現(xiàn) Converter 接口來協(xié)助 Spring MVC 完成數(shù)據(jù)類型的轉(zhuǎn)換,下面通過兩個案例來介紹如何自定義數(shù)據(jù)轉(zhuǎn)換器。
案例一:客戶端輸入 String 類型的日期數(shù)據(jù) “2021-09-16”,自定義轉(zhuǎn)換器將該數(shù)據(jù)轉(zhuǎn)為 Date 類型的對象。
Step1:創(chuàng)建 DateConverter 轉(zhuǎn)換器,實(shí)現(xiàn) org.springframework.core.convert.converter.Converter
接口,定義泛型為 <String,Date>
,將 String 類型的數(shù)值轉(zhuǎn)換為 Date 類型;
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> { //解析的模式串 private String pattern; public DateConverter(String pattern){ this.pattern = pattern; } @Override public Date convert(String s) { //轉(zhuǎn)換邏輯代碼 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.pattern); Date date = null; try { date = simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return date; } }
Step2:在 springmvc.xml 中配置轉(zhuǎn)換器;
- 配置
id="conversionService"
的 bean,bean 的類名稱必須是org.springframework.context.support.ConversionServiceFactoryBean
,bean 必須包含一個 converters 屬性,它將列出在應(yīng)用程序中用到的所有自定義數(shù)據(jù)轉(zhuǎn)換器。然后將我們自定義的 DateConverter 添加到 list 標(biāo)簽對中,通過有參構(gòu)造函數(shù)創(chuàng)建 DateConverter 對象; - 在
<mvc:annotation-driven />
標(biāo)簽元素的conversion-service
屬性添加 bean 名稱;
<!-- 配置自定義轉(zhuǎn)換器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.trainingl.converter.DateConverter"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg> </bean> </list> </property> </bean> <mvc:annotation-driven conversion-service="conversionService"> <!-- 消息轉(zhuǎn)換器 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property> </bean> <!-- 配置fastjson --> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean> </mvc:message-converters> </mvc:annotation-driven>
Step3:創(chuàng)建 addDate 視圖頁面,提交form 表單數(shù)據(jù)到后臺;
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/date" method="post"> 出生日期: <input type="date" name="birthday" /> <input type="submit" value="提交"> </form> </body> </html>
Step4:創(chuàng)建控制器的業(yè)務(wù)方法;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; @Controller public class DateHandler { @RequestMapping("/date") @ResponseBody public String userDate(Date birthday){ System.out.println(birthday); return birthday.toString(); } }
Step5:啟動 Tomcat 服務(wù)器,運(yùn)行程序;
案例二:注冊一個 Student 對象,前端頁面按照 “id-name-age” 的形式輸入 String 類型的數(shù)據(jù),通過轉(zhuǎn)換器,可以將該 String 類型的數(shù)據(jù)直接轉(zhuǎn)換為 Student 對象。
1、創(chuàng)建 Student 實(shí)體類;
package com.trainingl.entity; public class Student { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
2、創(chuàng)建 StudentConverter 轉(zhuǎn)換器;
import com.trainingl.entity.Student; import org.springframework.core.convert.converter.Converter; public class StudentConverter implements Converter<String, Student> { @Override public Student convert(String s) { //處理字符串信息 String[] args = s.split("-"); Student student = new Student(); student.setId(Long.parseLong(args[0])); student.setName(args[1]); student.setAge(Integer.parseInt(args[2])); return student; } }
3、springmvc.xml 中配置 StudentConverter 轉(zhuǎn)換器;
<!-- 配置自定義轉(zhuǎn)換器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.trainingl.converter.DateConverter"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg> </bean> <bean class="com.trainingl.converter.StudentConverter"> </bean> </list> </property> </bean>
4、創(chuàng)建 addStudent 視圖頁面;
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加新同學(xué)</title> </head> <body> <form action="/addStu" method="post"> 學(xué)生信息:<input type="text" name="student">(提示:id-name-age)<br/> <input type="submit" value="提交"> </form> </body> </html>
5、創(chuàng)建業(yè)務(wù)方法;
@Controller public class StudentHandler { @RequestMapping("/addStu") @ResponseBody public String addStudent(Student student){ System.out.println(student); return student.toString(); } }
啟動 Tomcat 服務(wù)器,運(yùn)行程序:
從返回的結(jié)果中看出,輸入的字符串信息被成功解析成了 Java 對象。
總結(jié):我們知道 http 表單中的所有請求參數(shù)都是 String 類型的,如果業(yè)務(wù)參數(shù)是 String 或者 int 類型,HandlerAdapter 組件可以自動完成數(shù)據(jù)轉(zhuǎn)換,但如果參數(shù)是其他數(shù)據(jù)類型,比如:格式化字符串等,HandlerAdapter 是不能自動將 String 類型轉(zhuǎn)換為 Date 類型或JavaBean 的,這時就需要開發(fā)者手動的創(chuàng)建自定義數(shù)據(jù)轉(zhuǎn)換器。
到此這篇關(guān)于Spring MVC 自定義數(shù)據(jù)轉(zhuǎn)換器的文章就介紹到這了,更多相關(guān)Spring MVC 自定義數(shù)據(jù)轉(zhuǎn)換器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java在cmd運(yùn)行"-d"和"-cp"參數(shù)解讀
這篇文章主要介紹了java在cmd運(yùn)行"-d"和"-cp"參數(shù)用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08mybatis insert 返回自增主鍵的實(shí)現(xiàn)示例
mybatis 在新增之后怎么也獲取不到自增主鍵,本文主要介紹了mybatis insert 返回自增主鍵的實(shí)現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2024-06-06SpringBoot整合Web開發(fā)之Json數(shù)據(jù)返回的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot整合Web開發(fā)其中Json數(shù)據(jù)返回的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Springcloud-nacos實(shí)現(xiàn)配置和注冊中心的方法
這篇文章主要介紹了Springcloud-nacos實(shí)現(xiàn)配置和注冊中心的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07數(shù)據(jù)定位在java購物車系統(tǒng)中的應(yīng)用
實(shí)現(xiàn)"加入購物車"功能,數(shù)據(jù)定位至關(guān)重要,它通過用戶ID和商品ID等標(biāo)識符實(shí)現(xiàn)快速查詢和數(shù)據(jù)一致性,主鍵、外鍵和聯(lián)合索引等數(shù)據(jù)庫技術(shù),以及Redis緩存和并發(fā)控制策略如樂觀鎖或分布式鎖,共同保障了購物車系統(tǒng)的查詢效率和數(shù)據(jù)安全,這些機(jī)制對高并發(fā)和大數(shù)據(jù)量的場景尤為重要2024-10-10Spring Cache @Cacheable 緩存在部分Service中不生效的解決辦法
這篇文章主要介紹了Spring Cache @Cacheable 緩存在部分Service中不生效的解決辦法2023-10-10