package common.utils.http;

import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;

public class MyController extends Controller {
	@NotAction
	public <T> T getJsonModel(Class<T> type) {
		return MyController.getJsonModelByRequestAndType(getRequest(), type);
	}
	
	public static <T> T getJsonModelByRequestAndType(HttpServletRequest request, Class<T> type) {
		String data = HttpKit.readData(request);
		
		// request只支持读取一次，无法满足需求
		if (StrKit.notBlank(data)) {
			request.setAttribute("data", data);
		} else {
			data = (String) request.getAttribute("data");
		}
		
		return FastJson.getJson().parse(data, type);
	}
}
