BaseController.java 2.44 KB
package com.diligrp.website.util.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.diligrp.website.util.web.exception.WebException;

/**
 * BaseController
 * 
 */
public class BaseController extends VelocitySupport {
	protected final static String DEFAULT_CHARTSET = "UTF-8";
	protected final static String DEFAULT_JSON_CONTENT_TYPE = "application/json;charset="
			+ DEFAULT_CHARTSET;

	/**
	 * 输出文本
	 * 
	 * @param txt
	 * @param contextType
	 */
	protected void write(HttpServletResponse response, String txt,
			String contextType) {
		try {
			if (StringUtils.isEmpty(txt)) {
				return;
			}
			response.setContentType(contextType);
			response.getOutputStream().write(txt.getBytes(DEFAULT_CHARTSET));
		} catch (Exception ex) {
			throw new WebException(ex);
		}
	}

	/**
	 * 输出JSON对象
	 * 
	 * @param model
	 */
	protected void writeJSON(HttpServletResponse response, Object model) {
		write(response, JSON.toJSONString(model), DEFAULT_JSON_CONTENT_TYPE);
	}

	protected Map<String, Object> getDefaultContext() {
		Map<String, Object> context = new HashMap<String, Object>();
		return context;
	}

	protected ViewBuilder toView(String template) {
		ViewBuilder vb = new ViewBuilder(template, this);
		return vb;
	}

	/**
	 * java bean to json
	 * 
	 * @param object
	 * @return
	 */
	protected String objectToJSON(Object object) {
		// try {
		// return new ObjectMapper().writeValueAsString(object);
		// } catch (JsonGenerationException e) {
		// e.printStackTrace();
		// } catch (JsonMappingException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		return "";
	}

	/**
	 * json to java bean
	 * 
	 * @param <T>
	 * @param jsonStr
	 * @param t
	 * @return
	 */
	protected <T> T JSONToObject(String jsonStr, Class<T> t) {
		// try {
		// return new ObjectMapper().readValue(jsonStr, t);
		// } catch (JsonParseException e) {
		// e.printStackTrace();
		// } catch (JsonMappingException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		return null;
	}

	protected void writeStringToResponse(HttpServletResponse response,
			String text) throws IOException {
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(text);
	}
}