spring mvc 參數綁定

来源:https://www.cnblogs.com/jdkman/archive/2018/11/12/9948848.html
-Advertisement-
Play Games

基礎類型 原始類型:id必須要傳,否則報錯。 包裝類型:id可以不傳,後臺接受到null。 list&set 簡單類型 前臺 form表單 ajax 後臺 複雜類型 如 :(略)同json格式對象 數組 前臺 form表單 ajax 後臺 map 前臺 form ajax 後臺 pojo簡單屬性 前 ...


基礎類型

原始類型:id必須要傳,否則報錯。

@RequestMapping("/test")
@ResponseBody
public ResponseData test(int id) {}

包裝類型:id可以不傳,後臺接受到null。

@RequestMapping("/test")
@ResponseBody
public ResponseData test(Integer id) {}

list&set

簡單類型

前臺

form表單

<form action="${ctx}/test/test" method="post">
    <input type="text" name="ids">
    <input type="text" name="ids">
    <input type="text" name="ids">
    <input type="submit">
</form>

ajax

var data = [];
data.push(1);
data.push(2);
data.push(3);
$.ajax({
    url: ctx + "/test/test",
    traditional:true,//必要
    data: {ids: data},
    success: function (result) {
        alert(result);
    }
})

後臺

@RequestMapping("/test")
@ResponseBody
public ResponseData test(@RequestParam List<Integer>ids) {}

複雜類型

list<User>users:(略)同json格式對象

數組

前臺

form表單

<form action="${ctx}/test/test" method="post">
    <input type="text" name="ids">
    <input type="text" name="ids">
    <input type="text" name="ids">
    <input type="submit">
</form>

ajax

var data = [];
data.push(1);
data.push(2);
data.push(3);
$.ajax({
    url: ctx + "/test/test",
    traditional:true,//必要
    data: {ids: data},
    success: function (result) {
        alert(result);
    }
})

後臺

@RequestMapping("/test")
@ResponseBody
public ResponseData test(Integer[]ids) {
}

map

前臺

form

<form action="${ctx}/test/test" method="post">
    <input type="text" name="name">
    <input type="text" name="sex">
    <input type="submit">
</form>

ajax

var data = {name:"zhangsan",sex:"man"};
$.ajax({
    url: ctx + "/test/test",
    data:data,
    success: function (result) {
        alert(result);
    }
});

後臺

@RequestMapping("/test")
@ResponseBody
public ResponseData test(@RequestParam Map<String,String> params) {}

pojo簡單屬性

前臺

form

<form action="${ctx}/test/test" method="post">
    <input type="text" name="name">
    <input type="text" name="sex">
    <input type="submit">
</form>

ajax

var data = {name:"zhangsan",sex:"man"};
$.ajax({
    url: ctx + "/test/test",
    data:data,
    success: function (result) {
        alert(result);
    }
});

後臺

@RequestMapping("/test")
@ResponseBody
public ResponseData test(User user) {}
public class User{
    private String name;
    private String sex;
    //get and set ...
}

pojo包含list

前臺

form

<form action="${ctx}/test/test" method="post">
    <input type="text" name="userName" value="zhangsan">
    <input type="text" name="sex" value="123">
    <input type="text" name="posts[0].code" value="232"/>
    <input type="text" name="posts[0].name" value="ad"/>
    <input type="text" name="posts[1].code" value="ad"/>
    <input type="text" name="posts[1].name" value="232"/>
    <input type="submit">
</form>

ajax

var user={userName:"zhangsan",password:"123"};
user['posts[0].name']="ada";
user['posts[0].code']="ada";
user['posts[1].name']="ad";
user['posts[1].code']="ad2323a";
$.ajax({
    url: ctx + "/test/test",
    type:"post",
    contentType: "application/x-www-form-urlencoded",
    data:user,
    success: function (result) {
        alert(result);
    }
});

後臺

public class User{
    private String name;
    private String sex;
    private List<Post> posts;
    //get and set ...
}
public class Post {
    private String code;
    private String name;
    //get and set ...
}
@RequestMapping("/test")
@ResponseBody
public ResponseData test(User user) {}

date類型

使用註解方式

綁定單個方法

對於傳遞參數為Date類型,可以在參數前添加@DateTimeFormat註解。如下:

@RequestMapping("/test")
public void test(@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date date){}

如果傳遞過來的是對象,可以在對象屬性上添加註解。

@RequestMapping("/test")
public void test(Person person){}

Public class Person{
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    Private Date date;
    Private String name;
}
綁定整個controller的所有方法:
@Controller
public class FormController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}
@Controller
public class FormController {
   @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }
}

使用PropertyEditor方式

使用ConversionService方式

參考:

https://www.2cto.com/kf/201501/374062.html

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-initbinder

枚舉類型

mvc配置文件添加:

 <!--枚舉類型轉化器-->
    <bean id="formattingConversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="org.springframework.core.convert.support.StringToEnumConverterFactory"/>
            </set>
        </property>
    </bean>

參考:

Spring Boot綁定枚舉類型參數

Spring MVC 自動為對象註入枚舉類型

json格式對象

後臺

@RequestMapping(value = "introductionData.do", method = {RequestMethod.POST})
@ResponseBody
public RestResult introductionData(@RequestBody SignData signData) {
}
public class SignData {
    private ApplicationInformation applicationInformation;
    private ApplyUserInformation applyUserInformation;
    private StudentInformation studentInformation;
    private List<VolunteerItem> volunteerItems;
    private ResidencePermit residencePermit;
    private List<Family> families;
    //get and set ...
}

前臺

var data = {}
var applyUserInformation = {
    "applyName": APPLYNAME,
    "applyCardType": "0",
    "applyCardID": APPLYIDCARD,
    "applyMobile": APPLYMOBILE
};
var applicationInformation = {
    "live_address": nowaddress,
    "addressJZArea": addressJZArea,
    "schoolLevel": schoolLevel,
    "schoolType": schoolType,
    "applyName": APPLYNAME,
    "contacts": contacts,
    "contactNumber": contactNumber
};
var studentInformation = {
    "cardType": cardType,
    "cardID": cardID,
    "studentName": studentName,
    "studentType": studentType,
    "studentType1": studentSpecialCase,
    "isDisability": "0",
    "studentCategory": "0",
    "birthday":birthday,
    "graduationschool":SchoolName,
    "graduationclass":classNameinfo,
    "applyName": APPLYNAME
};
data["applyUserInformation"] = applyUserInformation;
data["applicationInformation"] = applicationInformation;
data["studentInformation"] = studentInformation;

$.ajax({
    url: ctx + '/overseasData.do',
    type: "post",
    data: JSON.stringify(data),
    contentType: "application/json;charset=utf-8",
    success: function (result) {}
})

參考:https://blog.csdn.net/qq_29663071/article/details/68922043


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 隨著互聯網的興起,web開發變得愈發的重要。Python作為當前火熱的語言, 其中的web開發框架可以說是百花齊放,下麵聊一聊這些框架。 一: 基於Python的代表性Web框架 "Django" Django是一個開放源代碼的Web應用框架,由Python寫成。採用了MTV的框架模式,即模型M,模 ...
  • M:model代表的是應用的業務邏輯,通過Javabeen,EJB實現, V:view代表的是應用的表示面,有jsp頁面產生 C:controller提供應用的處理過程機制,一般是一個servlet,通過這種設計模型把應用邏輯,處理過程和顯示邏輯分成不同的組件實現。這些組件可以進行交互和重用 Jav ...
  • 1、一行代碼實現1-100的和 2、如何在一個函數內修改全局變數的值 3、字典如何刪除鍵和合併兩個字典 4、說一說對python的GIL的理解 GIL是python的全局解釋器鎖,在一個進程中如果有多個線程執行,其中一個線程在執行的時候會霸占python解釋器(加鎖即GIL),那麼其他線程就不能執行 ...
  • WIN7系統,VC2010下。 程式A靜態鏈接B.dll動態庫。 B.dll中導出3個類: (1) 基類 class AFX_EXT_CLASS base { public: base(){}; virtual ~base(){}; virtual int getX() = 0; protected ...
  • 一 、約束 python中約束有兩種 第一種,通過拋異常進行約束,這種是子類不按我要求的來,我就給你拋異常(推薦) 操作:提取一個父類. 在父類中給出一個方法。但在方法中不給出任何代碼,直接拋異常 1 # 貼吧 2 # 項目經理(級別高一點兒) 3 class Base: 4 def login(s ...
  • 2018年11月12日20:51:35 一、基礎知識: 1、JVM、JRE和JDK的區別: JVM(Java Virtual Machine):java虛擬機,用於保證java的跨平臺的特性。 java語言是跨平臺,jvm不是跨平臺的。 JRE(Java Runtime Environment):j ...
  • 按位與&: 只要對應的二個二進位都為1時,結果位就為1 按位或|:只要對應的二個二進位有一個為1時,結果位就為1 按位異或^:0⊕0=0,1⊕0=1,0⊕1=1,1⊕1=0(同為0,異為1) 按位非:取反操作符 ...
  • 在定義一個類的時候,有時我們需要獲取一個類的屬性值,而這個屬性值需要經過類中的其他屬性運算來獲得的。那麼很容易,只要我們在類中定義一個方法,並且通過調用方法可以獲取到那個需要運算的屬性值。那麼,問題來了,當有一天需求變了,你需要反向操作你之前實現的類,你需要通過傳入那個需要運算得來的值來獲取參與運算 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...