转载和引用,请注明原文出处! Fork me on GitHub
结局很美妙的事,开头并非如此!

SpringMVC系列(十一)把后台返回的数据转换成json、文件下载、文件上传

一、后台返回的数据转换成json

1、引入转换json需要的3个依赖

 1 <!--json转换需要的依赖 begin  -->
 2     <dependency>
 3       <groupId>com.fasterxml.jackson.core</groupId>
 4       <artifactId>jackson-annotations</artifactId>
 5       <version>2.9.2</version>
 6     </dependency>
 7     <dependency>
 8       <groupId>com.fasterxml.jackson.core</groupId>
 9       <artifactId>jackson-core</artifactId>
10       <version>2.9.1</version>
11       <type>jar.sha256</type>
12     </dependency>
13     <dependency>
14       <groupId>com.fasterxml.jackson.core</groupId>
15       <artifactId>jackson-databind</artifactId>
16       <version>2.9.2</version>
17     </dependency>
18     <!--json转换需要的依赖 end  -->

2、写handle

一定要加上注解@ResponseBody

1 @ResponseBody
2     @RequestMapping("/testJson")
3     public Collection<Employee> testJson(){
4         return employeeDao.getAll();
5     }

3、在index.jsp用ajax发请求

 1 <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
 2 <script type="text/javascript">
 3     $(function(){
 4         $("#testJson").click(function(){
 5             var url = this.href;
 6             var args = {};
 7             $.post(url, args, function(data){
 8                 for(var i = 0; i < data.length; i++){
 9                     var id = data[i].id;
10                     var lastName = data[i].lastName;
11                     
12                     alert(id + ": " + lastName);
13                 }
14             });
15             return false;
16         });
17     })
18 </script>
19 </head>
20 <body>
21     
22     <a href="testJson" id="testJson">Test Json</a>
23 </body>
24 </html>

查看请求响应结果

[
{"id":1001,"lastName":"E-AA","email":"aa@163.com","gender":1,"department":{"id":101,"departmentName":"D-AA"},"birth":null,"salary":null},
{"id":1002,"lastName":"E-BB","email":"bb@163.com","gender":1,"department":{"id":102,"departmentName":"D-BB"},"birth":null,"salary":null},
{"id":1003,"lastName":"E-CC","email":"cc@163.com","gender":0,"department":{"id":103,"departmentName":"D-CC"},"birth":null,"salary":null},
{"id":1004,"lastName":"E-DD","email":"dd@163.com","gender":0,"department":{"id":104,"departmentName":"D-DD"},"birth":null,"salary":null},
{"id":1005,"lastName":"E-EE","email":"ee@163.com","gender":1,"department":{"id":105,"departmentName":"D-EE"},"birth":null,"salary":null}
]

4、原理分析:使用HttpMessageConverter<T>转换

• HttpMessageConverter<T> 是 Spring3.0 新添加的一个接口,负责将请求信息转换为一个对象(类型为 T),将对象(类型为 T)输出为响应信息。

• 使用 HttpMessageConverter<T> 将请求信息转化并绑定到处理方法的入参中或将响应结果转为对应类型的响应信息,Spring 提供了两种途径:
– 使用 @RequestBody / @ResponseBody 对处理方法进行标注
– 使用 HttpEntity<T> / ResponseEntity<T> 作为处理方法的入参或返回值
• 当控制器处理方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T>/ResponseEntity<T> 时, Spring 首先根据请求头或响应头的Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的HttpMessageConverter 将报错
• @RequestBody 和 @ResponseBody 不需要成对出现

原理图如下:

 

 二、文件下载

1. 编写handle

 1 @RequestMapping("/testResponseEntity")
 2     public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
 3         byte [] body = null;
 4         ServletContext servletContext = session.getServletContext();
 5         InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
 6         body = new byte[in.available()];
 7         in.read(body);
 8         
 9         HttpHeaders headers = new HttpHeaders();
10         headers.add("Content-Disposition", "attachment;filename=abc.txt");
11         
12         HttpStatus statusCode = HttpStatus.OK;
13         
14         ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
15         return response;
16     }

2.在jsp页面发请求

1 <a href="testResponseEntity">Test ResponseEntity</a>

 三、文件上传

• Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的。Spring 用Jakarta Commons FileUpload技术实现了一个
MultipartResolver 实现类:CommonsMultipartResovler
• Spring MVC 上下文中默认没有装配 MultipartResovler,因此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 MultipartResolver

1.在pom.xml引入文件上传需要的依赖

 1  <dependency>
 2    <groupId>commons-fileupload</groupId>
 3    <artifactId>commons-fileupload</artifactId>
 4    <version>1.2.1</version>
 5  </dependency>
 6  <dependency>
 7    <groupId>commons-io</groupId>
 8    <artifactId>commons-io</artifactId>
 9    <version>2.0</version>
10  </dependency>

 

2.springmvc.xml里面配置MultipartResolver

• defaultEncoding: 必须和用户 JSP 的 pageEncoding 属性一致,以便正确解析表单的内容
• 为了让 CommonsMultipartResovler 正确工作,必须先将 Jakarta Commons FileUpload 及 Jakarta Commons io的类包添加到类路径下。

1 <!-- 配置 MultipartResolver -->
2     <bean id="multipartResolver"
3         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <property name="defaultEncoding" value="UTF-8"></property>
5         <property name="maxUploadSize" value="1024000"></property>    
6     </bean>    

 

3.编写handle

1 @RequestMapping("/testFileUpload")
2     public String testFileUpload(@RequestParam("desc") String desc, 
3             @RequestParam("file") MultipartFile file) throws IOException{
4         System.out.println("desc: " + desc);
5         System.out.println("OriginalFilename: " + file.getOriginalFilename());
6         System.out.println("InputStream: " + file.getInputStream());
7         return "success";
8     }

 

4.编写index.jsp

1 <form action="testFileUpload" method="POST" enctype="multipart/form-data">
2         File: <input type="file" name="file"/>
3         Desc: <input type="text" name="desc"/>
4         <input type="submit" value="Submit"/>
5   </form>

 

posted @ 2017-11-14 13:11  小不点啊  阅读(2335)  评论(0编辑  收藏  举报