Make Spring insist json in a easy way

在网上看了一些spring 支持json的方法,大致有两类:
一种是继承Controller.这种方法对于multi controller不方便。
一种是继承View.这种方法更麻烦,还需要对配置文件进行配置。
下面提供一个我一直用的,很简单方便。


/**
* Spring json callback class
*
* @Author [email protected]
*/
public abstract class JsonCallback {
	public void doInController(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("application/json;charset=utf-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			String jsonString=null;
			try {
				jsonString=this.createJson(request);
			} catch (Exception e) {
				e.printStackTrace();
				StringBuffer sb=new StringBuffer("{'result':'error','exception':{'message':'");
				sb.append(e.getMessage());
				sb.append("','stackTrace':'");	
				for(StackTraceElement st:e.getStackTrace()){
					sb.append("at ");
					sb.append(st.toString());
					sb.append("\n");
				}
				sb.append("'}");
				sb.append("'}");
				jsonString=sb.toString();
			}
			writer.println(jsonString);
		} catch (IOException ex1) {
			ex1.printStackTrace();
		} finally {
			writer.close();
		}
	}
	
	/*
	* sub class do with business in this method.
	*/
	protected abstract String createJson(HttpServletRequest request);
}



这里是用法:
	@RequestMapping("/json.htm") 	
	public void jsonMethod(HttpServletRequest request,HttpServletResponse response) {
		new JsonCallback() {
			protected String createJson(HttpServletRequest request) {
				return "{'name':'hello json'}";
			}
		}.doInController(request, response);
	}


你可能感兴趣的:(spring,json)