目录
九、HttpMessageConverter
1、@RequestBody
2、RequestEntity
3、@ResponseBody
4、SpringMVC将对象转化成json
5、SpringMVC处理ajax
6、@RestController注解(非常重要)
7、ResponseEntity(实现文件下载)
十、文件上传和下载
1、文件下载
2、文件上传
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,ResponseEntity
@RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值
@RequestMapping("/testRequestBody")
//使用@RequestBody获取请求体
public String testRequestBody(@RequestBody String requestBody) throws UnsupportedEncodingException {
//输出请求体,并将url解码
System.out.println("requestBody:"+ URLDecoder.decode(requestBody, "UTF-8"));
return "success";
}
输出结果:requestBody:username=张三&password=12345
RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息
@RequestMapping("/testRequestEntity")
//使用RequestEntity将请求报文封装为java对象
public String testRequestEntity(RequestEntity requestEntity) throws UnsupportedEncodingException {
//获取请求头
System.out.println("请求头:"+requestEntity.getHeaders());
//获取请求体
System.out.println("请求体:"+URLDecoder.decode(requestEntity.getBody(),"UTF-8"));
return "success";
}
输出结果:
请求头:[host:"localhost:8080", connection:"keep-alive", content-length:"40", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"", sec-ch-ua-mobile:"?0", sec-ch-ua-platform:""Windows"", 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/102.0.5005.63 Safari/537.36", accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", sec-fetch-user:"?1", sec-fetch-dest:"document", referer:"http://localhost:8080/springMVC_demo4/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9,en-GB;q=0.8,en-US;q=0.7,en;q=0.6", cookie:"Idea-87c2ee2b=73b3225d-f813-4b7a-aec7-ff8cc48ee37e", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
请求体:username=张三&password=123
使用servletAPI的Response对象来响应浏览器数据
测试servletAPI的Response对象来响应浏览器数据
@RequestMapping("/testResponse")
public void testResponse(HttpServletResponse response) throws IOException {
//设置编码,解决中文乱码
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("你好! hello,response");
}
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
响应数据中文乱码解决办法https://blog.csdn.net/qq_57389269/article/details/123798992
测试@ResponseBody响应浏览器数据
@RequestMapping(value = "/testResponseBody", produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"})
@ResponseBody
public String testResponseBody(){
//不加@ResponseBody,则返回的是一个视图名称,加上则就表示一个纯字符串
return "成功";
}
@ResponseBody处理json的步骤:
a>导入jackson的依赖
com.fasterxml.jackson.core
jackson-databind
2.13.3
b>在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串
c>在控制器方法上使用@ResponseBody注解进行标识
d>将Java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串
实体类:
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
public User() {
}
public User(Integer id, String username, String password, Integer age, String sex) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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;
}
}
控制器方法:
@RequestMapping(value = "/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"张三","12345",22,"男");
}
链接:
测试@ResponseBody响应浏览器User对象
a>请求超链接:
b>通过vue和axios处理点击事件:
在SpringMVC.xml文件配置
c>控制器方法:
@RequestMapping("/testAxios")
@ResponseBody
public String testAxios(String username, String password){
System.out.println(username + ',' + password);
return "hello,axios";
}
提示:在axios中已经阻止页面跳转,执行弹框,如果还是跳转,重新执行maven打包
@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解
ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
使用ResponseEntity实现下载文件的功能
下载测试
@RequestMapping("/testDown")
public ResponseEntity testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/mm景色.jpeg");
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=mm景色.jpeg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
另一种方式参考文件下载https://blog.csdn.net/m0_62520968/article/details/124900717?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165503555116780357235899%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165503555116780357235899&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-124900717-null-null.nonecase&utm_term=%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD&spm=1018.2226.3001.4450
文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
a>添加依赖:
commons-fileupload
commons-fileupload
1.4
b>在SpringMVC的配置文件中添加配置:
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";
}
上传到target的SNAPSHOT