SpringBoot - 请求报文与响应报文 @RequestBody,@ResponseBody,RequestEntity,ResponseEntity
1.@RequestBody
获取请求体
一般用来获取前端穿过来的JSON数据,如果传过来的不是JSON数据格式 会报错
@RequestMapping(value="meta") public String meta(@RequestBody String requestBody,@RequestBody ReUser user){ return "Success"; }
2.@ResponseBody
返回响应体给前端,作用类上与方法上
3.RequestEntity
RequestEntity类型用于获取整个请求报文,包括请求头、请求体等信息。
@RequestMapping(value="meta") public String meta(RequestEntity<String> requestEntity){ return "Success"; }
4.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; }
响应数据:
@RequestMapping(value="meta") public ResponseEntity<String> meta(){ //响应体 String body="<h1>Hello,World</h1>"; //响应头 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type","text/html;charset=UTF-8"); //响应码 HttpStatus httpStatus=HttpStatus.OK; return new ResponseEntity<String>(body,httpHeaders,httpStatus); }
posted on 2022-12-30 19:22 Mikasa-Ackerman 阅读(619) 评论(0) 编辑 收藏 举报