1. 控制層
private SqlSessionFactoryBean sqlSessionFactory ;
@ResponseBody
@RequestMapping(value = "f3")
public String f3( @RequestBody SearchMap searchMap,HttpServletRequest request, HttpServletResponse response) {
SqlSession session = null;
try {
SqlSessionFactory object = sqlSessionFactory.getObject();
String sqlId = request.getParameter("sqlId");
Page<SearchMap> page = new Page<SearchMap>(request, response);// 相互插入
searchMap.setPage(page);
session = object.openSession();
List<SearchMap> listMap = session.selectList(sqlId, searchMap);
page.setList(listMap);
return JsonMapper.toJsonString(page); // 查詢結果爲0,則返回page爲0的記錄
}catch(Exception e){
Result resultError = new Result();
resultError.setCode("false");
resultError.setMessage(e.toString());//
// log4j.輸出信息!
return JsonMapper.toJsonString(resultError); // 若是查詢語句不存在,則拋出異常!
}
finally {
session.close();
}
}
接受的參數相似
public class SearchMap extends HashMap<String, String>{
/**
* 當前實體分頁對象
*/
protected Page<SearchMap> page;
public Page<SearchMap> getPage() {
return page;
}
public void setPage(Page<SearchMap> page) {
this.page = page;
}
}
sql語句
<select id="get2" resultType="map">
SELECT
<include refid="testDataColumns"/>
FROM test_data a
</select>
返回錯誤代碼
public class Result{
private String message;
private String code;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
2. 前端代碼
function page(n,s){ // 下一頁
$.ajax({
url :'${ctx}/test/testData/f3?sqlId=test.get2&pageNo='+n+'&pageSize='+s,
type: 'post',
dataType : "json",
contentType:'application/json;charset=UTF-8',//關鍵是要加上這行
data : JSON.stringify( {id:'22',remarks:'aaa'}),
async : false, // 同步請求
success : function(data) {
if(data.code=='false'){
alert("代碼錯誤!");
console.log("錯誤代碼是:"+data.message);
}else{
$('#pageId').html(data.html);
}
}
});
}
初始化頁面
$.ajax({
url :'${ctx}/test/testData/f3?sqlId=test.get2',
type: 'post',
dataType : "json",
contentType:'application/json;charset=UTF-8',//關鍵是要加上這行
data : JSON.stringify( {id:'222',remarks:'aaa'}),
async : false, // 同步請求
success : function(data) {
if(data.code=='false'){
alert("代碼錯誤!");
console.log("錯誤代碼是:"+data.message);
}else{
$('#pageId').html(data.html);
}
}
});