springmvc处理ajax请求
生活随笔
收集整理的這篇文章主要介紹了
springmvc处理ajax请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.controller將數據封裝成json格式返回頁面
@RequestMapping("/dataList") public void datalist(CsoftCunstomerPage page,HttpServletResponse response) throws Exception{List<CsoftCunstomer> dataList = csoftCunstomerService.queryByList(page);//設置頁面數據Map<String,Object> jsonMap = new HashMap<String,Object>();jsonMap.put("total",page.getPager().getRowCount());jsonMap.put("rows", dataList);try {//設置頁面不緩存response.setContentType("application/json");response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setCharacterEncoding("UTF-8");PrintWriter out= null;out = response.getWriter();out.print(JSONUtil.toJSONString(jsonMap));out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}2.ajax提交數據以json格式到controller中
例一:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><!--<script type="text/javascript" src="../static/js/jquery-1.7.2.min.js"></script>--><!--JS的地址可以寫成下面這樣,將來部署的時候,這些靜態文件就可以單獨部署了,不依賴于后臺路徑--><script type="text/javascript" src="http://localhost:8080/sshdemo/static/js/jquery-1.7.2.min.js"></script><script type="text/javascript">$(document).ready(function() {ajaxRequest();});function ajaxRequest() {$.ajax({url: "http://localhost:8080/sshdemo/hello/ajax",type: "POST",dataType: "json",data: {"a": 1,"b": 2,"c": 3},async: false,success: function(data) {alert("success");$.each(data, function(index, element) {alert(element.a);alert(element.b);alert(element.c);});},error: function() {alert("error");}});}</script></head><body><div>Hello World!</div></body> </html> package com.xbs.ready.ssh.controller;import com.alibaba.fastjson.JSON; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;/**** @author xbs*/ @Controller @RequestMapping("hello") public class HelloController {/*** ajax請求不需要返回頁面,只需要得到response中的數據即可,所以方法簽名為void即可* * @param request* @param response */@RequestMapping(value = "ajax", method = RequestMethod.POST)public void ajaxDatas(HttpServletRequest request, HttpServletResponse response) {String jsonResult = getJSONString(request);renderData(response, jsonResult);}private String getJSONString(HttpServletRequest request) {//故意構造一個數組,使返回的數據為json數組,數據更復雜些List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>(5);Map<String, Object> map1 = new HashMap<String, Object>(10);//可以獲得ajax請求中的參數map1.put("a", request.getParameter("a"));map1.put("b", request.getParameter("b"));map1.put("c", request.getParameter("c"));datas.add(map1);//故意構造一個數組,使返回的數據為json數組,數據更復雜些Map<String, Object> map2 = new HashMap<String, Object>(10);map2.put("a", "11");map2.put("b", "22");map2.put("c", "33");datas.add(map2);String jsonResult = JSON.toJSONString(datas);return jsonResult;}/*** 通過PrintWriter將響應數據寫入response,ajax可以接受到這個數據* * @param response* @param data */private void renderData(HttpServletResponse response, String data) {PrintWriter printWriter = null;try {printWriter = response.getWriter();printWriter.print(data);} catch (IOException ex) {Logger.getLogger(HelloController.class.getName()).log(Level.SEVERE, null, ex);} finally {if (null != printWriter) {printWriter.flush();printWriter.close();}}} }例二:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html><head><title>helloworld</title> <script type="text/javascript" src="/spring_mvc/js/jquery.js"></script> <script type="text/javascript">$(function(){$("#testButton").click(function(){var $a = $(this);$.ajax({url:"/spring_mvc/testAjax.do",type:'post',data:'name=admin&password=123456',dataType:'html',success:function(data,status){if(status == "success"){var objs = jQuery.parseJSON(data);var str = "";for(var i=0;i<objs.length;i++){str = str + objs[i].activityName+" ";}$("#content").html(str);}},error:function(xhr,textStatus,errorThrown){}});});}); </script></head><body><button id="testButton">異步傳輸</button><div id="content"></div></body> </html> public class TestAjaxAction implements Controller {public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {response.setCharacterEncoding("UTF-8");String name = request.getParameter("name");String password = request.getParameter("password");System.out.println(name+" : "+password);PrintWriter out = response.getWriter();List<Map<String,String>> list = new ArrayList<Map<String,String>>();Map<String,String> m1 = new HashMap<String,String>();m1.put("activityId", "000001");m1.put("activityName", "阿斯蒂芬1");Map<String,String> m2 = new HashMap<String,String>();m2.put("activityId", "000002");m2.put("activityName", "阿斯蒂芬2");Map<String,String> m3 = new HashMap<String,String>();m3.put("activityId", "000003");m3.put("activityName", "阿斯蒂芬3");Map<String,String> m4 = new HashMap<String,String>();m4.put("activityId", "000004");m4.put("activityName", "阿斯蒂芬4");Map<String,String> m5 = new HashMap<String,String>();m5.put("activityId", "000005");m5.put("activityName", "阿斯蒂芬5");list.add(m1);list.add(m2);list.add(m3);list.add(m4);list.add(m5);String s = JSONArray.fromObject(list).toString();out.print(s);out.close();return null;}}例三:
@RequestMapping("/dataList") public void datalist(CsoftCunstomerPage page,HttpServletResponse response) throws Exception{List<CsoftCunstomer> dataList = csoftCunstomerService.queryByList(page);//設置頁面數據Map<String,Object> jsonMap = new HashMap<String,Object>();jsonMap.put("total",page.getPager().getRowCount());jsonMap.put("rows", dataList);try {//設置頁面不緩存response.setContentType("application/json");response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setCharacterEncoding("UTF-8");PrintWriter out= null;out = response.getWriter();out.print(JSONUtil.toJSONString(jsonMap));out.flush();out.close();} catch (IOException e) {e.printStackTrace();}} 分類: JAVA 好文要頂 關注我 收藏該文 左正關注 - 29
粉絲 - 126 +加關注 0 0 ? 上一篇:取maven copy部分
? 下一篇:SpringMVC 學習筆記(二) @RequestMapping、@PathVariable等注解
posted @ 2017-02-25 23:59 左正 閱讀(156) 評論(0) 編輯 收藏 刷新評論刷新頁面返回頂部 (評論功能已被禁用) 最新IT新聞:
· 摩拜發布共享單車與城市可持續發展報告:上海起最早、抗霾最積極
· 保溫杯+枸杞:究竟是中年人的孤單,還是年輕人的狂歡?
· 滴滴與美團將在哪些領域火力全開?
· 蓋茨J.P.摩根健康大會演講:生命科學研究可挽救數百萬人的生命
· 微博云剪2.0版本上線 2 分鐘制作一個短視頻
? 更多新聞... 最新知識庫文章:
· 步入云計算
· 以操作系統的角度述說線程與進程
· 軟件測試轉型之路
· 門內門外看招聘
· 大道至簡,職場上做人做事做管理
? 更多知識庫文章... 歷史上的今天:
2016-02-25 深入分析 Javascript 單線程
公告
本文轉自左正博客園博客,原文鏈接:http://www.cnblogs.com/soundcode/p/6443347.html,如需轉載請自行聯系原作者總結
以上是生活随笔為你收集整理的springmvc处理ajax请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt之对话框设计——淡入淡出效果
- 下一篇: exchange2013警告The ma