八、HttpMessageConverter
HttpMessageConverter,報文信息轉換器,將請求報文轉換為Java對象,或將Java對象轉換為響應報文
HttpMessageConverter提供了兩個注解和兩個類型:@RequestBody,@ResponseBody,RequestEntity,
ResponseEntity
1、@RequestBody
@RequestBody可以獲取請求體,需要在控制器方法設置一個形參,使用@RequestBody進行標識,當前請求的請求體就會為當前注解所標識的形參賦值
<form th:action="@{/testRequestBody}" method="post">用戶名:<input type="text" name="username"><br>密碼:<input type="password" name="password"><br><input type="submit">
</form>
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){System.out.println("requestBody:"+requestBody);return "success";
}
輸出結果:
requestBody:username=admin&password=123456
2、RequestEntity
RequestEntity封裝請求報文的一種類型,需要在控制器方法的形參中設置該類型的形參,當前請求的請求報文就會賦值給該形參,可以通過getHeaders()獲取請求頭信息,通過getBody()獲取請求體信息
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){System.out.println("requestHeader:"+requestEntity.getHeaders());System.out.println("requestBody:"+requestEntity.getBody());return "success";
}
輸出結果:
requestHeader:[host:“localhost:8080”, connection:“keep-alive”, content-length:“27”, cache-control:“max-age=0”, sec-ch-ua:“” Not A;Brand";v=“99”, “Chromium”;v=“90”, “Google Chrome”;v=“90"”, sec-ch-ua-mobile:“?0”, upgrade-insecure-requests:“1”, origin:“http://localhost:8080”, user-agent:“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36”]
requestBody:username=admin&password=123
3、@ResponseBody
@ResponseBody用于標識一個控制器方法,可以將該方法的返回值直接作為響應報文的響應體響應到瀏覽器
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){return "success";
}
結果:瀏覽器頁面顯示success
4、SpringMVC處理json
@ResponseBody處理json的步驟:
a>導入jackson的依賴
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.1</version>
</dependency>
b>在SpringMVC的核心配置文件中開啟mvc的注解驅動,此時在HandlerAdaptor中會自動裝配一個消息轉換器:MappingJackson2HttpMessageConverter,可以將響應到瀏覽器的Java對象轉換為Json格式的字符串
<mvc:annotation-driven />
c>在處理器方法上使用@ResponseBody注解進行標識
d>將Java對象直接作為控制器方法的返回值返回,就會自動轉換為Json格式的字符串
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){return new User(1001,"admin","123456",23,"男");
}
瀏覽器的頁面中展示的結果:
{“id”:1001,“username”:“admin”,“password”:“123456”,“age”:23,“sex”:“男”}
5、SpringMVC處理ajax
a>請求超鏈接:
<div id="app"><a th:href="@{/testAjax}" @click="testAjax">testAjax</a><br>
</div>
b>通過vue和axios處理點擊事件:
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript">var vue = new Vue({el:"#app",methods:{testAjax:function (event) {axios({method:"post",url:event.target.href,params:{username:"admin",password:"123456"}}).then(function (response) {alert(response.data);});event.preventDefault();}}});
</script>
c>控制器方法:
@RequestMapping("/testAjax")
@ResponseBody
public String testAjax(String username, String password){System.out.println("username:"+username+",password:"+password);return "hello,ajax";
}
6、@RestController注解
@RestController注解是springMVC提供的一個復合注解,標識在控制器的類上,就相當于為類添加了@Controller注解,并且為其中的每個方法添加了@ResponseBody注解
7、ResponseEntity
ResponseEntity用于控制器方法的返回值類型,該控制器方法的返回值就是響應到瀏覽器的響應報文
九、文件上傳和下載
1、文件下載
使用ResponseEntity實現下載文件的功能
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {//獲取ServletContext對象ServletContext servletContext = session.getServletContext();//獲取服務器中文件的真實路徑String realPath = servletContext.getRealPath("/static/img/1.jpg");//創建輸入流InputStream is = new FileInputStream(realPath);//創建字節數組byte[] bytes = new byte[is.available()];//將流讀到字節數組中is.read(bytes);//創建HttpHeaders對象設置響應頭信息MultiValueMap<String, String> headers = new HttpHeaders();//設置要下載方式以及下載文件的名字headers.add("Content-Disposition", "attachment;filename=1.jpg");//設置響應狀態碼HttpStatus statusCode = HttpStatus.OK;//創建ResponseEntity對象ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);//關閉輸入流is.close();return responseEntity;
}
2、文件上傳
文件上傳要求form表單的請求方式必須為post,并且添加屬性enctype=“multipart/form-data”
SpringMVC中將上傳的文件封裝到MultipartFile對象中,通過此對象可以獲取文件相關信息
上傳步驟:
a>添加依賴:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version>
</dependency>
b>在SpringMVC的配置文件中添加配置:
<!--必須通過文件解析器的解析才能將文件轉換為MultipartFile對象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
c>控制器方法:
@RequestMapping("/testUp")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {//獲取上傳的文件的文件名String fileName = photo.getOriginalFilename();//處理文件重名問題String hzName = fileName.substring(fileName.lastIndexOf("."));fileName = UUID.randomUUID().toString() + hzName;//獲取服務器中photo目錄的路徑ServletContext servletContext = session.getServletContext();String photoPath = servletContext.getRealPath("photo");File file = new File(photoPath);if(!file.exists()){file.mkdir();}String finalPath = photoPath + File.separator + fileName;//實現上傳功能photo.transferTo(new File(finalPath));return "success";
}