一 ajax带简单参数请求
controller
import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(Model model) {
return "testParam";
}
@RequestMapping(value = "test")
@ResponseBody
public Map test(String name, Integer age) throws Exception {
Map result = new HashMap<>();
result.put("name", name);
result.put("age", age);
return result;
}
}
jsp
$.ajax({
url: 'test.json',
type: 'post',
data: {
name: '二狗',
age: 3
},
async: true,
cache: false,
success: function (data) {
console.log(JSON.stringify(data));
}
});
页面
20180824092236.png
二 ajax带数组参数请求
controller
import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(Model model) {
return "testParam";
}
/**
* @param name
* @param food 页面的food:[1,2,3]会已 food[]:1,food[]:2,food[]:3形式发送过来,所以这里要给food参数起个food[]别名,这样才能接收到
* @return
* @throws Exception
*/
@RequestMapping(value = "test")
@ResponseBody
public Map test(String name, @RequestParam(name = "food[]") String[] food) throws Exception {
Map result = new HashMap<>();
result.put("name", name);
result.put("food", food);
return result;
}
}
jsp
$.ajax({
url: 'test.json',
type: 'post',
data: {
name: '二狗',
food: ['狗粮','骨头','营养膏']
},
async: true,
cache: false,
success: function (data) {
console.log(JSON.stringify(data));
}
});
页面
20180824093032.png
三 ajax带对象请求
实体类
package com.pandabus.custom.controller;
public class Dog {
private String name;
private String[] food;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getFood() {
return food;
}
public void setFood(String[] food) {
this.food = food;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
controller
import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(Model model) {
return "testParam";
}
/***
*
* @param dog 需要添加@RequestBody注解,这样SpringMvc会把收到的JSON反序列化成实体
* @return
* @throws Exception
*/
@RequestMapping(value = "test")
@ResponseBody
public Map test(@RequestBody Dog dog) throws Exception {
Map result = new HashMap<>();
result.put("dog", dog);
return result;
}
}
JSP
var dog = {
name: '二狗',
food: ['狗粮', '骨头', '营养膏'],
age: 3
};
$.ajax({
url: 'test.json',
type: 'post',
contentType: 'application/json',//需要指定contentType
data: JSON.stringify(dog),//传递对象的json
async: true,
cache: false,
success: function (data) {
console.log(JSON.stringify(data));
}
});
页面
20180824093911.png
四 ajax表单上传文件
controller
import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(Model model) {
return "testParam";
}
/***
*
* @param file 必须指定@RequestParam
* @return
* @throws Exception
*/
@RequestMapping(value = "test")
@ResponseBody
public Map test(@RequestParam(name = "file") CommonsMultipartFile file) throws Exception {
Map result = new HashMap<>();
result.put("content", readFile(file));
return result;
}
private List readFile(CommonsMultipartFile file) throws IOException {
List result = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
result.add(line);
}
return result;
} catch (Exception ex) {
throw ex;
} finally {
if (reader != null) {
reader.close();
}
}
}
}
JSP
上传
$("#btn_upload").click(function () {
var option = {
url: "test.json",
type: "POST",
async: true,
success: function (data) {
console.log(JSON.stringify(data));
}
};
$("#uploadTxtForm").ajaxSubmit(option); //ajax 提交表单
});
页面
20180824101930.png
五 ajax同时提交文件和参数
controller
import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(Model model) {
return "testParam";
}
/***
*
* @param file 必须指定@RequestParam
* @return
* @throws Exception
*/
@RequestMapping(value = "test")
@ResponseBody
public Map test(@RequestParam(name = "file") CommonsMultipartFile file, String storyName) throws Exception {
Map result = new HashMap<>();
result.put("content", readFile(file));
result.put("storyName", storyName);
return result;
}
private List readFile(CommonsMultipartFile file) throws IOException {
List result = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
result.add(line);
}
return result;
} catch (Exception ex) {
throw ex;
} finally {
if (reader != null) {
reader.close();
}
}
}
}
JSP
提交
$("#btn_upload").click(function () {
var option = {
url: "test.json",
type: "POST",
async: true,
success: function (data) {
console.log(JSON.stringify(data));
}
};
$("#uploadTxtForm").ajaxSubmit(option); //ajax 提交表单
});
页面
20180824102920.png
六 Java代码同时上传代码和附件
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public final class Test {
public static void main(String[] args) throws IOException {
HttpPost httpPost = new HttpPost("http://xxxx:8080/yyyy//deviceConfig/uploadLogs.json");
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse resp = null;
String respondBody = null;
try {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", new File("/var/root/Desktop/aaa.txt"));//附件
multipartEntityBuilder.addTextBody("logOperationId", "18");//普通参数
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
resp = client.execute(httpPost);
respondBody = EntityUtils.toString(resp.getEntity());
System.out.println(respondBody);
} catch (IOException | ParseException e) {
e.printStackTrace();
} finally {
resp.close();
}
}
}
@ResponseBody
@RequestMapping(value = "uploadLogs")
public Map uploadLogs(@RequestParam("file") CommonsMultipartFile file, Integer logOperationId) throws Exception {
Map result = new HashMap<>();
//TODO 操作参数
return result;
}
Java代码上传file和text
public static void main(String[] args) throws IOException {
HttpPost httpPost = new HttpPost("http://localhost:8080/long_river/xxx/yyy.json");
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse resp = null;
String respondBody = null;
try {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("files", new File("/var/root/Desktop/testMap.html"));
multipartEntityBuilder.addBinaryBody("files", new File("/var/root/Desktop/menu.html"));
multipartEntityBuilder.addTextBody("deviceIds", "18");
multipartEntityBuilder.addTextBody("deviceIds", "19");
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
resp = client.execute(httpPost);
respondBody = EntityUtils.toString(resp.getEntity());
System.out.println(respondBody);
} catch (IOException | ParseException e) {
e.printStackTrace();
} finally {
resp.close();
}
}