HttpMessageConverter
HttpMessageConverter:报文信息转换器,将请求报文转换为Java对象,或者将Java对象转换为相应报文。所拥有两个注解和两个类型:
- @RequestBody
- @ResponseBody
- RequestEntity
- ResponseEntity
@RequestBody
可以获取情感求体,需要在控制器方法设置一个形参,使用 @RequestBody 进行标识,当前请求的请求体就会为当前注解所标识的形参赋值。
<!DOCTYPE html>
<html lang="en" xmlns:th="http:/www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<form th:action="@{/testRequestBody}" method="post">
用户名:<input type="text" name="user_name"/></br>
密码:<input type="password" name="password"/></br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class indexController {
@RequestMapping("/")
public String LocateIndexPage() {
return "index";
}
@RequestMapping(value = "/testRequestBody", method=RequestMethod.POST)
public String testRequestBody(@RequestBody String requestBody) {
System.out.println("requestBody:"+requestBody);
return "success";
}
}
RequestEntity
RequestEntity封装请求报文的一种类型,报文会赋值给该形参,通过getHeader获取头信息,通过getBody获取请求体信息。
package com.controller;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class indexController {
@RequestMapping("/")
public String LocateIndexPage() {
return "index";
}
@RequestMapping(value = "/testRequestBody", method=RequestMethod.POST)
public String testRequestBody(RequestEntity<String> requestEntity) {
System.out.println(requestEntity.getHeaders());
System.out.println(requestEntity.getBody());
System.out.println(requestEntity.getMethod());
return "success";
}
}
@ResponseBody
package com.controller;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class indexController {
@RequestMapping("/")
public String LocateIndexPage() {
return "index";
}
@RequestMapping(value = "/testRequestBody", method=RequestMethod.POST)
@ResponseBody
public String testRequestBody(RequestEntity<String> requestEntity) {
return requestEntity.getHeaders() + "\n" + requestEntity.getBody()+"\n" + requestEntity.getMethod();
}
}
将对象变为json格式
创建User对象
package com.entity;
public class User {
private Integer id;
private String user_name;
private String password;
private Integer age;
private String sex;
public User() {}
public User(Integer id, String user_name, String password, Integer age, String sex) {
super();
this.id = id;
this.user_name = user_name;
this.password = password;
this.age = age;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
主页
<!DOCTYPE html>
<html lang="en" xmlns:th="http:/www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/testResponseUser}">响应User对象</a>
</body>
</html>
controller
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.entity.User;
@Controller
public class indexController {
@RequestMapping("/")
public String LocateIndexPage() {
return "index";
}
@RequestMapping(value = "/testResponseUser")
@ResponseBody
public User testRequestUser() {
return new User(1001,"admin","123456",23,"男");
}
}
此处是可以直接解析为json格式的字符串,因为SpringBoot已经引入了处理该对象的包。
@RestController
即,@ResponseBody+@Controller,使得该控制器下的组件都有了 @ResponseBody 注解。
ResponseEntity
该方法用于控制器方法的返回值类型。即,自定义的相应报文。常用于文件下载部分。
上传与下载
主页代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http:/www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/down}">下载文件1</a>
<form th:action="@{/up}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo">
<input type="submit" value="提交"/>
</form>
</body>
</html>
下载
我们在webapp下,放置一个1.jpg文件,作为我们要下载的文件。
- 此处注意,如果用的不是SpringBoot自带的tomcat,请放置在resource的static中。
- 笔者是通过Maven来进行项目的,因此用的是Spring Boot自带的Tomcat。此处的webapp是不存在的,需要自己创建。如果没有,此处的getRealPath会定位到SpringBoot Tomcat的临时路径中寻找,导致查找失败。(因为它是Servlet的原生方法,如果不设置则找不到static)
- 创建后,我们会发现类似于我们JavaWeb的文件结构
- 此外,建议不要通过当前的整个储存的方式传输文件,可以通过流的方式进行传输,避免溢出。可以用Servlet的response或者FileSystemResource或为ResponseEntity中放入OutputStream来执行。
package com.controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FileupdownController {
@RequestMapping("/down")
public ResponseEntity<byte[]> downTheFile(HttpSession session) throws IOException{
ServletContext servletContext = session.getServletContext();
String realPath = servletContext.getRealPath("/1.jpg");
System.out.println(realPath);
InputStream is = new FileInputStream(realPath);
byte[] bytes = new byte[is.available()];
is.read(bytes);
MultiValueMap<String,String> headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=1.jpg");
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,headers,statusCode);
is.close();
return responseEntity;
}
}
上传
SpringBoot已经帮我们设置好了需要的解析器和Jar包。我们直接使用即可。
我们可以在application.properties处,控制上传的大小
#设置单个文件上传大小,默认大小:1MB,
spring.servlet.multipart.max-file-size=1MB
#设置总上传文件的大小,默认大小:10MB,
spring.servlet.multipart.max-request-size=10MB
package com.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileupdownController {
@RequestMapping("/up")
public String upTheFile(MultipartFile photo,HttpSession session)throws Exception {
String fileName = photo.getOriginalFilename();
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("/photo");
File file = new File(photoPath);
if(!file.exists()) {
file.mkdir();
}
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString().replaceAll("-","");
fileName = uuid+suffixName;
photoPath = photoPath + File.separator + fileName;
photo.transferTo(new File(photoPath));
return "success";
}
}
- 多文件使用**MultipartFile[]**数组来接收。
- 可以同时上传文件和其他文本等信息。接收方式同之前一样,不需要一个个比对。
其他部分,可参考Spring Boot的文件上传与下载
参考资源
|