當jQuery 發送ajax請求需要傳遞多個參數時,如果參數過多,Controller接收參數時就需要定義多個參數,這樣接口方法會比較長,也不方便。Spring可以傳遞對象參數,將你需要的所有查詢條件定義成對象的屬性,前台給對象賦值,后台Controller接收時只需要接收對象參數即可,這樣代碼就變得非常簡潔。以下是示例代碼:
1、對象參數QueryBean
就是普通的java類,定義你需要的屬性,生產getter、setter方法即可。例如我查詢時需要傳遞用戶名稱name、用戶密碼password,那么我的類:Class User{private String name;private String password;getter....setter....}
2、前台jsp頁面jQuery發送請求如何傳入對象參數userEntity。要注意data里是JSON格式字符串,屬性與對象參數User里的屬性名稱完全一致。
$.ajax({
type : "post",
url :"${pageContext.request.contextPath }/customerController/queryMedicalRecords",
data :{name:'這里是你需要傳遞的用戶名稱值',password:'你輸入的密碼’},
dataType : "json",
success : function(res) {
}
});
3、后台Spring Controller 接收參數方法。方法中定義一個對象參數User對象即可,對象名稱隨便寫。這樣前台的參數在方法里可以直接通過userEntity.get...方法來拿到。接口里只有request、response、userEntity三個參數,非常干凈整潔。如果不是用這樣的方法的話,那么就需要定義成這樣:public void queryMedicalRecords( HttpServletRequest request, HttpServletResponse response,String name,String password)。這樣看起來就很冗余了。
public void queryMedicalRecords( HttpServletRequest request, HttpServletResponse response,User userEntity) throws IOException {.....}