1、HttpMessageConverter
1、ResponseBody
2、RequestEntity
3、@ResponseBody
4、SpringMVC处理json
5、SpringMVC处理ajax
6、@RestController注解
7、ResponseEntity
2、文件上传和下载
1、文件下载
2、文件上传
@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
RequestEntity封装请求报文的一种类型,表示整个请求报文的信息,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息。
<form th:action="@{/testRequestEntity}" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="测试testRequestEntity">
</form>
@RequestMapping(value="/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
System.out.println("headers:" + requestEntity.getHeaders());
//headers:[host:"localhost:8080", connection:"keep-alive", content-length:"23", cache-control:"max-age=0", sec-ch-ua:"" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"", sec-ch-ua-mobile:"?0", sec-ch-ua-platform:""macOS"", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 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_war_exploded/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
System.out.println("body:" + requestEntity.getBody());
//body:username=11&password=22
System.out.println("method:" + requestEntity.getMethod());
//method:POST
System.out.println("url:" + requestEntity.getUrl());
//url:http://localhost:8080/SpringMVC_war_exploded/testRequestEntity
System.out.println("type:" + requestEntity.getType());
//type:class java.lang.String
return "success";
}
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
@RequestMapping(value="/testResponse")
public void testResponse(HttpServletResponse response) throws IOException {
response.getWriter().print("success");
}
@RequestMapping(value="/testResponseBody")
@ResponseBody
public String testResponseBody(HttpServletResponse response){
return "success";
}
结果:
浏览器页面显示 success
//实体类对象转化为json:为json对象
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"admin","123456",23,"男");
//{"id":1001,"username":"admin","password":"123456","age":23,"gender":"男"}
}
//list转化为json:为json数组
@RequestMapping("/testResponseList")
@ResponseBody
public List<User> testResponseList(){
List<User> list = new ArrayList<>();
list.add(new User(1001,"admin","123456",23,"男"));
list.add(new User(1002,"admin2","1234562",23,"女"));
return list;
/**
* [ {"id":1001,"username":"admin","password":"123456","age":23,"gender":"男"},
* {"id":1002,"username":"admin2","password":"1234562","age":23,"gender":"女"}
* ]
*/
}
//map集合转化为json:json对象
@RequestMapping("/testResponseMap")
@ResponseBody
public Map<Integer,User> testResponseMap(){
Map<Integer,User> map = new HashMap<>();
map.put(1,new User(1001,"admin","123456",23,"男"));
map.put(2,new User(1002,"admin2","1234562",23,"女"));
return map;
/**
* { "1":{"id":1001,"username":"admin","password":"123456","age":23,"gender":"男"},
* "2":{"id":1002,"username":"admin2","password":"1234562","age":23,"gender":"女"}
* }
*/
}
@ResponseBody处理json的步骤:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<mvc:annotation-driven />
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"admin","123456",23,"男");
}
浏览器的页面中展示的结果:
{“id”:1001,“username”:“admin”,“password”:“123456”,“age”:23,“sex”:“男”}
<div id="app">
<a th:href="@{/testAjax}" @click="testAjax">testAjax</a><br>
</div>
<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>
@RequestMapping("/testAjax")
@ResponseBody
public String testAjax(String username, String password){
System.out.println("username:"+username+",password:"+password);
return "hello,ajax";
}
使用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;
}
文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
@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";
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/mingyuli/article/details/122678275
内容来源于网络,如有侵权,请联系作者删除!