欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工具类 - 基于 Gson 的 JsonUtil 支持跨域

程序员文章站 2022-07-14 18:24:00
...
package com.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class JsonUtil {
	
	public JsonUtil(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
	}

	/** 当前HttpServletRequest */
	protected HttpServletRequest request;
	/** 当前HttpServletResponse */
	protected HttpServletResponse response;
	
	protected PrintWriter writer;

	public PrintWriter getWriter() {
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return writer ;
	}

	public void setWriter(PrintWriter writer) {
		this.writer = writer;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	// JSON
	private void setJsonHeader(){
		HttpServletResponse response = getResponse();
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers", "Authentication");
	}

	/**
	 * 警告:请不要直接使用此函数,防止产生缓存问题
	 * 请考虑使用outObjString
	**/
	public void outString(String str) {
		try {
			PrintWriter out = getResponse().getWriter();
			out.print(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void outObjString(Object obj, String code, String msg) {
		setJsonHeader();
		String jsonString =
				"{" +
				" \"code\": \"" + code + "\"," +
				" \"msg\": \"" + msg + "\", " +
				" \"data\": " + new Gson().toJson(obj) +
				"}";
		outString(jsonString);
	}
	
	public void outObjString(Object obj) {
		setJsonHeader();
		String jsonString = "{\"success\":true,\"data\":" + new Gson().toJson(obj) + "}";
		outString(jsonString);
	}

}

调用示例:

JsonUtil out = new JsonUtil(request, response);
out.outObjString(Object, "状态码", "状态描述");

 

 

相关标签: 开发类