工具类积累(一)——Response向前台发送各种异步数据

Posted on 2016-04-04 11:07  Iltxy  阅读(1627)  评论(0)    收藏  举报

  今天开始在利用JSON向后台异步上传数据的时候,涉及到了一个图片的路径的回显工作!(以便在前台显示)是使用的AJAX异步提交并采用JSON数据!最后就涉及到了向前台发送JSON数据!情景描述清楚了,代码如下:

 1 package cn.ilxy.web;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 /**
 8  * 异步返回各种格式数据:json xml text
 9  * 
10  * @author: Robert
11  * @date: 2016年3月23日
12  */
13 public class ResponseUtils {
14     private ResponseUtils() {
15         
16     }
17 
18     // 发送内容 "application/json;charset=UTF-8"
19     public static void render(HttpServletResponse response, String contentType, String text) {
20         response.setContentType(contentType);
21         try {
22             response.getWriter().write(text);
23         } catch (IOException e) {
24             e.printStackTrace();
25         }
26     }
27 
28     // 发送的是JSON
29     public static void renderJSON(HttpServletResponse response, String text) {
30         render(response, "application/json;charset=UTF-8", text);
31     }
32 
33     // 发送xml
34     public static void renderXml(HttpServletResponse response, String text) {
35         render(response, "application/xml;charset=UTF-8", text);
36     }
37 
38     // 发送text
39     public static void renderText(HttpServletResponse response, String text) {
40         render(response, "application/plain;charset=UTF-8", text);
41     }
42 }

  接下来就是愉快的使用了!

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3