Java代码
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object cmd, BindException ex) { String userId=request.getParamater("userId"); Map userInfoMap=userDao.getUserBaseInfo(userId); JSONObject object = new JSONObject(); object.put("userInfoMap",userInfoMap); response.setContentType("text/Xml;charset=gbk"); PrintWriter out = null; try { out = response.getWriter(); out.println(object.toString()); } catch (IOException ex1) { ex1.printStackTrace(); }finally{ out.close(); } return null; }
说明一下我向客户端页面response的是一个JSon对象,选择JSon这种数据格式的两个原因是:
使用Spring Mvc原有的SimpleFormController,从上边的例子上看是可以实现的,但是每次都要写"将JSonObject写入流,关流的代码.很累,很麻纺."
所以,扩展了两个新的Controller,以简化对Ajax请求的处理.
JSONObjectAbstractController 用于简单的从request.getParamater参数的情况.
JSONObjectAbstractController 的原代码:
Java代码
package com.javaest.ext.spring.mvc.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public abstract class JSONObjectAbstractController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject jsonObject = handleAjaxRequestInternal(request, response); response.setContentType("text/Xml;charset=gbk"); PrintWriter out = null; try { out = response.getWriter(); out.println(jsonObject.toString()); } catch (IOException ex1) { ex1.printStackTrace(); } finally { out.close(); } return null; } protected abstract JSONObject handleAjaxRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception; }
JSONObjectSimpleFormController 用于自动将请求参数绑定到Command对象的情况.
JSONObjectSimpleFormController 的代码:
Java代码
注:JSONObject 是json-lib-2.3-jdk15.jar中的,请自己下载导入
本文是转载