Action向前台输出

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ResponseJsonUtils {

public static void write(String str){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.write(str);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void write(Object obj){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
try {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String result = gson.toJson(obj);
PrintWriter out = response.getWriter();
out.write(result);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void writeSimpleJson(boolean success, String msg) {
String jsonStr = "{\"success\":" + success + ",\"msg\":\"" + msg + "\"}";
write(jsonStr);
}
}

上一篇:XML 解析技术


下一篇:【OpenGL游戏开发之二】OpenGL常用API