SpringMVC參數綁定學習總結【先後端數據參數傳遞】

SpringMVC做爲Controller層(等價servlet和struts中的action)專門用來處理頁面的一些請求,而後將數據再經過視圖返回給用戶的,所以可見先後端數據參數傳遞相對springmvc的重要性,這篇文章將總結一下springmvc中如何接收前臺頁面的參數,即springmvc中的參數綁定問題。 @[toc]html

1. 綁定機制

表單提交的數據都是k=v格式的,SpringMVC的參數綁定過程是把表單提交的請求參數,做爲控制器中方法的參數進行綁定的,但要注意一點,提交表單的name和controller方法的參數名稱是相同的java

2. 支持的數據類型

springmvc中,有支持的默認類型的綁定,可見springmvc框架的強大~框架就是強~。也就是說,直接在controller方法形參上定義默認支持的類型對象,就可使用下面這些對象。web

HttpServletRequest對象 HttpServletResponse對象 HttpSession對象 Model/ModelMap對象spring

支持的數據類型有基本數據類型、包裝類、字符串類型、實體類型(JavaBean) 、集合數據類型(List、map集合等),那麼下面就來具體分析分析。數據庫

2.一、基本數據類型、字符串

其實下面測試類我已經包括基本數據類型、包裝類、字符串類型了! controller測試代碼後端

@Controller
@RequestMapping("/param")
public class ParamController {
    @RequestMapping("/testBaseParam")
    public String testParam(String username,int password,Integer san){
        System.out.println("testParam執行了...");
        System.out.println("用戶名:"+username);
        System.out.println("密碼:"+password);
        System.out.println("密碼:"+san);
        return "success";
    }
複製代碼

index.jsp測試代碼mvc

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>測試基礎類型</h3>
    <a href="param/testBaseParam?username=劉備胎&password=123&san=456">請求參數綁定</a>
</body>
</html>

複製代碼

運行效果 app

在這裏插入圖片描述
再次強調,注意提交表單的name和參數的名稱必須相同,不然綁定失敗
在這裏插入圖片描述
基本數據類型、包裝類、字符串類型總結:一、提交表單的name和參數的名稱必須相同。二、嚴格區分大小寫

2.二、實體類型(JavaBean)

第一種狀況:正常實體類

dao測試代碼框架

//實現可序列化接口
public class Account implements Serializable{
//Account數據庫字段
    private String username;
    private String password;
    private Double money;


...省去getset方法和toString方法
複製代碼

controller測試代碼jsp

//請求參數綁定把數據封裝到JavaBean的類中
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("saveAccount執行了...");
        System.out.println(account);
        return "success";
    }
複製代碼

這裏用index.jsp轉發到了param.jsp,代碼以下:

<jsp:forward page="param.jsp"></jsp:forward>
複製代碼

param.jsp測試代碼以下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    把數據封裝Account類中
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密碼:<input type="text" name="password" /><br/>
        金額:<input type="text" name="money" /><br/>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

複製代碼

測試效果

在這裏插入圖片描述
第一種狀況總結:注意提交表單的name和參數的名稱必須相同,不然綁定失敗~強調n次了~

第二種狀況:實體類包含對象屬性

dao測試代碼,注意Account實體類中包含User對象屬性

//實現可序列化接口
public class Account implements Serializable{
//Account數據庫字段
    private String username;
    private String password;
    private Double money;
//User對象屬性
    private User user;
    
...省去getset方法和toString方法
複製代碼

User實體類代碼

//實現可序列化接口
public class User implements Serializable{
    private String uname;
    private Integer age;
    private Date date;

...省去getset方法和toString方法
複製代碼

controller測試代碼沒變,因此就不貼出來了。 param.jsp測試代碼以下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    把數據封裝Account類中
    <form action="param/saveAccount" 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="提交" />
    </form>
</body>
</html>

複製代碼

測試效果

在這裏插入圖片描述
細心的同窗可能發現了,date屬性爲null,由於我沒有在jsp中給date傳值因此爲null。 第二種狀況總結:實體類包含對象屬性這種狀況,先後端傳參jsp格式:實體對象.對應實體類屬性字段

2.三、集合數據類型(List、map集合等)

dao測試類代碼:

//實現可序列化接口 
public class Account implements Serializable{
//Account數據庫字段
    private String username;
    private String password;
    private Double money;
//集合對象屬性
    private List<User> list;
    private Map<String,User> map;
  
...省去getset方法和toString方法
複製代碼

controller測試代碼

//請求參數綁定把數據封裝到帶集合類型的JavaBean的類中
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("saveAccount執行了...");
        System.out.println(account);
        return "success";
    }
複製代碼

param.jsp測試代碼以下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
     把數據封裝Account類中,類中存在list和map的集合
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密碼:<input type="text" name="password" /><br/>
        金額:<input type="text" name="money" /><br/>

        用戶姓名:<input type="text" name="list[0].uname" /><br/>
        用戶年齡:<input type="text" name="list[0].age" /><br/>

        用戶姓名:<input type="text" name="map['one'].uname" /><br/>
        用戶年齡:<input type="text" name="map['one'].age" /><br/>
        <input type="submit" value="提交" />
    </form>

</body>
</html>

複製代碼

測試效果

在這裏插入圖片描述
總結:集合類型jsp格式:list[0].屬性

3. 參數請求中文亂碼解決

通過上面測試,有的同窗可能會出現中文亂碼問題,這是很正常的,由於咱們沒有設置相似request.setCharacterEncoding("UTF-8") 操做,爲了防止中文亂碼解決,咱們能夠統一設置全局編碼過濾器。 在web.xml中配置Spring提供的過濾器類

<!--配置解決中文亂碼的過濾器-->
  <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>
複製代碼

4.自定義類型轉換器

既然springmvc強大到提供默認支持不少類型,可是仍是存在瑕疵,例如咱們在保存date日期類型的數據時,springmvc只支持2019/9/18 該種格式,若是換成2019-8-18 則將報錯,那我也不能光說不作鴨,下面我就再來踩一次坑,讓你們LookLook,這裏會報The server cannot or will not process the request due to something that is perceived to be a client error異常,不過沒事,我也寫了專門決絕該異常的一篇文章,點擊進入,不扯了,開始測試 jsp關鍵代碼

用戶生日:<input type="date" name="user.date" /><br/>
複製代碼

報錯效果:

在這裏插入圖片描述
爲了跟有力的證實我剛說的springmvc只支持 2019/9/18 該種格式,若是換成 2019-8-18 則將報錯,那麼我就把jsp關鍵代碼更改了一下,把type=date改爲了type=text,以下

用戶生日:<input type="text" name="user.date" /><br/>
複製代碼

效果以下

在這裏插入圖片描述
咱們想一想,表單提交的任何數據類型所有都是字符串類型,可是後臺定義Integer類型,數據也能夠封裝上,說明Spring框架內部會默認進行數據類型轉換。若是想自定義數據類型轉換,該怎麼實現呢?

4.1建立一個普通類實現Converter接口

一、建立一個普通類實現Converter接口,並添加相應格式轉換方法,代碼以下

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/** * 把字符串轉換日期 */
public class StringToDateConverter implements Converter<String,Date>{

    /** * String 傳入進來字符串 */
    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("完蛋~數據類型轉換出現錯誤");
        }
    }

}

複製代碼

4.2Springmvc.xml中配置自定義類型轉換器

  1. 註冊自定義類型轉換器,在springmvc.xml配置文件中編寫配置
<!--配置自定義類型轉換器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.gx.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>


    <!-- 開啓SpringMVC框架註解的支持 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
複製代碼

效果以下:

在這裏插入圖片描述
自定義類型轉換器步驟總結: 一、建立一個普通類實現Converter接口,並添加相應格式轉換方法 二、註冊自定義類型轉換器,在springmvc.xml配置文件中編寫配置

千萬別忘了配置以後要在註解驅動中註冊,也就是這一句

<mvc:annotation-driven conversion-service="conversionService"/>
複製代碼

五、最後參數綁定學習小結

在這裏插入圖片描述

若是本文對你有一點點幫助,那麼請點個讚唄,謝謝~

最後,如有不足或者不正之處,歡迎指正批評,感激涕零!若是有疑問歡迎留言,絕對第一時間回覆!

歡迎各位關注個人公衆號,一塊兒探討技術,嚮往技術,追求技術,說好了來了就是盆友喔...

在這裏插入圖片描述
相關文章
相關標籤/搜索