一.ajax功能
SpringMVC快速的完成ajax功能?
1)返回数据是json就可以了。
2)页面$.ajax{};
原生的Java Web:
1)导入GSON
2)返回的数据将GSON转成json
3)写出去
1.1 ajax 获取所有员工
1)导包
jackson-annotations-2.1.5.jar
jackson-core-2.1.5.jar
jackson-databind-2.1.5.jar
2)编写目标方法,使其返回JSON对应的对象或集合。
package com.test.controller;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.test.bean.Employee;
import com.test.dao.EmployeeDao;
@Controller
public class AjaxController {
@Autowired
EmployeeDao employeeDao;
/*
* 将返回的数据放在响应体中
* 如果是对象,自动将对象转为json格式
*/
@ResponseBody
@RequestMapping("/getallAjax")
public Collection<Employee> ajaxgetAll(){
Collection<Employee> all=employeeDao.getAll();
return all;
}
}
3)增加页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<a href="${ctp }/getallAjax">ajax获取所有员工</a>
<div>
</div>
<script type="text/javascript">
$("a:first").click(function(){
//1.发送ajax获取所有员工
$.ajax({
url:"${ctp}/getallAjax",
type:"GET",
success:function(data){
console.log(data);
$.each(data.function(){
var empInfo=this.lastName+"--->"+this.birth+"----->"+this.gender;
$("div").append(empInfo+"<br/>");
});
}
});
return false;
});
</script>
</body>
</html>
4)测试:

1.2 ajax与@RequestBody(获取请求体)结合:发送json数据给服务器
1)处理器方法:
/*
* @RequestBody:请求体,获取一个请求的请求体,接收json数据
* @RequestParam:
*/
@RequestMapping("/testResuestBody")
public String testResuestBody(@RequestBody Employee employee){
return "success";
}
2)页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
<body>
<form action="${ctp }/testResuestBody" method="post">
<input name="username" value="tomcat"/>
<input name="password" value="12345"/>
<input type="submit"/>
</form>
<a href="testResuestBody"> ajax发送JSon数据</a>
</body>
<script type="text/javascript">
$("a:first").click(function(){
var emp={
lastName:"张三",
email:"aaa@com.com",
gender:0
};
//js对象
//alert(typeof emp);
var empStr=JSON.stringify(emp);
//alert(typeof empStr);
$.ajax({
url:'${ctp}/testResuestBody',
type:"POST",
data:empStr,
contentType:"application/json",
success:function(data){
alert(data);
}
});
return false;
});
</script>
</html>
二.HttpMessageConverter
2.1 HttpMessageConverter<T>
HttpMessageConverter<T>是Spring 3.0新增加的一个接口,负责将请求信息转换为一个对象(类型为T),将对象(类型为T)输出为响应信息。
HttpMessageConverter<T>接口定义的方法:
- Boolean canRead(Class<?> clazz,MediaType mediaType): 指定转换器可以读取的对象类型,即转换器是否可将请求信息转换为 clazz 类型的对象,同时指定支持 MIME 类型(text/html,applaiction/json等)
- Boolean canWrite(Class<?> clazz,MediaType mediaType):指定转换器是否可将 clazz 类型的对象写到响应流中,响应流支持的媒体类型在MediaType 中定义。
- List<MediaType> getSupportMediaTypes():该转换器支持的媒体类型。
- T read(Class<? extends T> clazz,HttpInputMessage inputMessage):将请求信息流转换为 T 类型的对象。
- void write(T t,MediaType contnetType,HttpOutputMessgae outputMessage):将T类型的对象写到响应流中,同时指定相应的媒体类型为 contentType。


DispatchServlet默认装配RequestMappingHandlerAdapter,而RequestMappingHandlerAdapter默认装配HttpMessageConverter:

加入jackson.jar包后,RequestMappingHandlerAdapter装配的HttpMessageConverter如下:

默认情况下数组长度是6个;增加了jackson的包,后多个一个MappingJackson2HttpMessageConverter

2.2 使用HttpMessageConverter
使用 HttpMessageConverter<T> 将请求信息转化并绑定到处理方法的入参中或将响应结果转为对应类型的响应信息,Spring 提供了两种途径:
- 使用 @RequestBody / @ResponseBody 对处理方法进行标注
- 使用 HttpEntity<T> / ResponseEntity<T> 作为处理方法的入参或返回值
当控制器处理方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T>/ResponseEntity<T> 时, Spring 首先根据请求头或响应头的 Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的 HttpMessageConverter 将报错
@RequestBody 和 @ResponseBody 不需要成对出现
2.3 ResponseEntity应用:文件下载
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{
//找到要下载的文件的真实路径
ServletContext context=request.getServletContext();
String realPath=context.getRealPath("/scripts/jquery-1.9.1.min.js");
//1.得到要下载的文件流
FileInputStream is=new FileInputStream(realPath);
byte[] tmp=new byte[is.available()];
is.read(tmp);
is.close();
HttpHeaders headers=new HttpHeaders();
headers.set("Content-Disposition", "attachment;filename="+"jquery-1.9.1.min.js");
//2.将要下载的文件流返回
return new ResponseEntity<byte[]>(tmp,headers,HttpStatus.OK);
}
2.4 实验代码
@RequestMapping("/test01")
public String test01(@RequestBody String str){
System.out.println("请求体"+str);
return "success";
}
/*
* 如果参数位子写HttpEntity<String> str
* 比@RequesBody强大,可以拿到请求头
*/
@RequestMapping("/test02")
public String test02(HttpEntity<String> str){
System.out.println(str);
return "success";
}
/*
* @ResponseBody:可以把对象转为json数据,返回给浏览器。将返回数据放在响应体中(返回字符串)
* @RequestBody:接收json数据,封装对象
*
* ResponseEntity<String>:响应体中内容的类型
*/
@RequestMapping("/haha")
public ResponseEntity<String> haha(){
MultiValueMap<String, String> headers = new HttpHeaders();
String body="<h1>success</h1>";
headers.add("Set-Cookie", "username=hhhh");
return new ResponseEntity<String>(body,headers,HttpStatus.OK);
}
来源:CSDN
作者:WYFVV
链接:https://blog.csdn.net/WYFVV/article/details/104196160