文章目錄
一、@ResponseBody註解
1.導包
2.@ResponseBody返回json數據
@ResponseBody註解
標在方法上,方法就返回json數據。
@Autowired
EmployeeDao employeeDao;
/**
* 將返回的數據放在響應體中.
* 如果是對象,自動轉換爲json格式
*/
@ResponseBody
@RequestMapping("/getallajax")
public Collection<Employee> ajaxGetAll() {
Collection<Employee> all = employeeDao.getAll();
return all;
}
訪問項目http://localhost:8080/6.SpringMVC_CRUD/getallajax
瀏覽器顯示結果如下:
[{"id":1001,"lastName":"E-AA","email":"[email protected]","gender":1,"department":
{"id":101,"departmentName":"D-AA"},"birth":null},{"id":1002,"lastName":"E-
BB","email":"bb@163.com","gender":1,"department":{"id":102,"departmentName":"D-
BB"},"birth":null},{"id":1003,"lastName":"E-
CC","email":"cc@163.com","gender":0,"department":{"id":103,"departmentName":"D-
CC"},"birth":null},{"id":1004,"lastName":"E-
DD","email":"dd@163.com","gender":0,"department":{"id":104,"departmentName":"D-
DD"},"birth":null},{"id":1005,"lastName":"E-
EE","email":"ee@163.com","gender":1,"department":{"id":105,"departmentName":"D-
EE"},"birth":null}]
3.使用ResponseEntity既能返回響應數據還能定製響應頭
@RequestMapping("/haha")
public ResponseEntity<String> haha() {
String body = "<h1>success</h1>";
MultiValueMap<String, String> headers = new HttpHeaders();// 自定義響應頭
HttpStatus statusCode;
headers.add("Set-Cookie", "username=hahahaha");
return new ResponseEntity<String>(body, headers, HttpStatus.OK);
}
二、@RequestBody註解
1.@RequestBody獲取請求體內容
handler處理器
// @RequestBody獲取一個請求的請求體
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body) {
System.out.println("請求體:" + body);
return "success";
}
前端頁面
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%
pageContext.setAttribute("ctp",request.getContextPath());
%>
</head>
<body>
<form action="${ctp }/testRequestBody" method="POST" enctype="multipart/form-data">
<input name="username" value="tomcat"/>
<input name="passworld" value="123456"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
點擊提交成功打印出請求體
打印結果:
請求體:-----------------------------7e43752205b6
Content-Disposition: form-data; name="username"
tomcat
-----------------------------7e43752205b6
Content-Disposition: form-data; name="passworld"
123456
-----------------------------7e43752205b6
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream
-----------------------------7e43752205b6--
2.@RequestBody獲取請求數據
前端頁面
- 通過ajax發送json請求給服務器。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
</head>
<script type="text/javascript" src="jQuery/jQuery-3.4.1.js"></script>
<body>
<a href="${ctp }/testRequestBody">ajax發送json數據</a> //點擊發送ajax請求
</body>
<script type="text/javascript">
$("a:first").click(function() {
var emp = {
lastname : "張三",
email : "[email protected]",
gender : 1
};
var empStr = JSON.stringify(emp);//將js對象轉換爲json對象
$.ajax({
url : '${ctp}/testRequestBody',
type : "POST",
data : empStr,
contentType : "application/json",
success : function(data) {
alert(data)
}
});
return false;
});
</script>
</html>
處理器
- 使用
@RequestBody
註解,可以接收json數據,將請求體中的數據封裝爲Employee 對象。
// @RequestBody可以獲取一個請求的請求體
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody Employee employee) {
System.out.println("請求體:" + employee);
return "success";
}
3.使用HttpEntity獲取請求體的同時獲取請求頭
- 除了使用@RequestBody獲取請求體內容,還可以使用HttpEntity來獲取請求頭和請求體的內容。
@RequestMapping("/test01")
public String test01(HttpEntity<String> str) {
System.out.println(str);
return "success";
}
三、HttpMessageConverter
HttpMessageConverter<T>
是Spring3.0新添加的一個接口,負責將請求信息轉換爲一個對象,(類型爲T),將對象(類型爲T)輸出爲響應信息。
HttpMessageConverter接口定義的方法:
Boolean canRead(Class<?> class,MediaType mediaType)
:指定轉換器可以讀取的對象類型,即轉換器是否可以將請求信息轉換爲class類型的對象,同時指定支持MIME類型(text/html,application/json)。Boolean canWrite(Class<?> class,MediaType mediaType)
:指定轉換器是否可將class類型的對象寫到響應流中,響應流支持的媒體類型在MediaType中定義。List<MediaType> getSupportMediaTypes()
:該轉換器支持的媒體類型。T read(Class<? extends T> class,HttpInputMessage inputMessage)
:將請求信息流轉換爲T類型的對象。void write(T t,MediaType contentType,HttpOutputMessage outputMessage)
:將T類型的對象寫到響應流中,同時指定相應的媒體類型爲contentType。