赞
踩
packagecom.siyang.CommonUtil;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.PrintWriter;importjavax.servlet.http.HttpServletResponse;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importcom.google.gson.Gson;public classBaseController {protected Logger logger =LoggerFactory.getLogger(getClass());/*** 输出JSON数据
*
*@paramresponse
*@paramjsonStr*/
public voidwriteJson(HttpServletResponse response, String jsonStr) {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter pw= null;try{
pw=response.getWriter();
pw.write(jsonStr);
pw.flush();
}catch(Exception e) {
logger.info("输出JSON数据异常", e);
}finally{if(pw!=null){
pw.close();
}
}
}/***
* 向页面响应json字符数组串流.
*
*@paramresponse
*@paramjsonStr
*@throwsIOException
*@returnvoid
*@author蒋勇
* @date 2015-1-14 下午4:18:33*/
public void writeJsonStr(HttpServletResponse response, String jsonStr) throwsIOException {
OutputStream outStream= null;try{
response.reset();
response.setCharacterEncoding("UTF-8");
outStream=response.getOutputStream();
outStream.write(jsonStr.getBytes("UTF-8"));
outStream.flush();
}catch(IOException e) {
logger.info("输出JSON数据异常(writeJsonStr)", e);
}finally{if(outStream!=null){
outStream.close();
}
}
}public void writeJsonStr(HttpServletResponse response, InputStream in) throwsIOException {if(null ==in ){return;
}
OutputStream outStream= null;try{
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
outStream=response.getOutputStream();int len = 0;byte[] byt = new byte[1024];while ((len = in.read(byt)) != -1) {
outStream.write(byt,0, len);
}
outStream.flush();
}catch(IOException e) {
logger.info("输出JSON数据异常(writeJsonStr)", e);
}finally{if(outStream!=null){
outStream.close();
in.close();
}
}
}/*** 输出JSON数据
*
*@paramresponse
*@paramjsonStr*/
public voidwriteJson(HttpServletResponse response, Object obj) {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter pw= null;
Gson gson= newGson();try{
pw=response.getWriter();
pw.write(gson.toJson(obj));
pw.flush();
}catch(Exception e) {
logger.info("输出JSON数据异常", e);
}finally{if(pw!=null){
pw.close();
}
}
}public voidwriteHtml(HttpServletResponse response, String html) {
response.setContentType("text/html;;charset=utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter pw= null;try{
pw=response.getWriter();
pw.write(html);
pw.flush();
}catch(Exception e) {
logger.info("输出HTML数据异常", e);
}finally{if(pw!=null){
pw.close();
}
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。