java怎么处理ajax请求_springmvc处理ajax请求

1.controller将数据封装成json格式返回页面

48304ba5e6f9fe08f3fa1abda7d326ab.png

@RequestMapping("/dataList")

public void datalist(CsoftCunstomerPage page,HttpServletResponse response) throws Exception{

List dataList = csoftCunstomerService.queryByList(page);

//设置页面数据

Map jsonMap = new HashMap();

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();

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

2.ajax提交数据以json格式到controller中

例一:

48304ba5e6f9fe08f3fa1abda7d326ab.png

/p>

"http://www.w3.org/TR/html4/loose.dtd">

$(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");

}

});

}

Hello World!

48304ba5e6f9fe08f3fa1abda7d326ab.png

48304ba5e6f9fe08f3fa1abda7d326ab.png

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> datas = new ArrayList>(5);

Map map1 = new HashMap(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 map2 = new HashMap(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();

}

}

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

例二:

48304ba5e6f9fe08f3fa1abda7d326ab.png

helloworld

$(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

str = str + objs[i].activityName+" ";

}

$("#content").html(str);

}

},

error:function(xhr,textStatus,errorThrown){

}

});

});

});

异步传输

48304ba5e6f9fe08f3fa1abda7d326ab.png

48304ba5e6f9fe08f3fa1abda7d326ab.png

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> list = new ArrayList>();

Map m1 = new HashMap();

m1.put("activityId", "000001");

m1.put("activityName", "阿斯蒂芬1");

Map m2 = new HashMap();

m2.put("activityId", "000002");

m2.put("activityName", "阿斯蒂芬2");

Map m3 = new HashMap();

m3.put("activityId", "000003");

m3.put("activityName", "阿斯蒂芬3");

Map m4 = new HashMap();

m4.put("activityId", "000004");

m4.put("activityName", "阿斯蒂芬4");

Map m5 = new HashMap();

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;

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

例三:

48304ba5e6f9fe08f3fa1abda7d326ab.png

@RequestMapping("/dataList")

public void datalist(CsoftCunstomerPage page,HttpServletResponse response) throws Exception{

List dataList = csoftCunstomerService.queryByList(page);

//设置页面数据

Map jsonMap = new HashMap();

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();

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值