Passing JSON object from Controller to View(jsp)
I am trying to send JSON object to my view from controller but unable to send it. Please help me out!
I am using following code
public class SystemController extends AbstractController{
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("SystemInfo", "System", "S");
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
JSONObject jsonResult = new JSONObject();
jsonResult.put("JVMVendor", System.getProperty("java.vendor"));
jsonResult.put("JVMVersion", System.getProperty("java.version"));
jsonResult.put("JVMVendorURL", System.getProperty("java.vendor.url"));
jsonResult.put("OSName", System.getProperty("os.name"));
jsonResult.put("OSVersion", System.getProperty("os.version"));
jsonResult.put("OSArchitectire", System.getProperty("os.arch"));
response.getWriter().write(jsonResult.toString());
// response.getWriter().close();
return mav; // return modelandview object
}
}
and in the view side I am using
<script type="text/javascript">
Ext.onReady(function(response) {
//Ext.MessageBox.alert('Hello', 'The DOM is ready!');
var showExistingScreen = function () {
Ext.Ajax.request({
url : 'system.htm',
meth开发者_如何转开发od : 'POST',
scope : this,
success: function ( response ) {
alert('1');
var existingValues = Ext.util.JSON.decode(response.responseText);
alert('2');
}
});
};
return showExistingScreen();
});
For sending JSON back to the client I successfully use the following solution:
1) client (browser) sends an AJAX POST containing JSON formatted values (but GET also possible) request to my SpringMVC controller.
$.postJSON("/login", login, function(data)
{
checkResult(data);
});
2) The SpringMVC controller method signature:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody Map<String, String>
login(@RequestBody LoginData loginData,
HttpServletRequest request, HttpServletResponse response)
@ResponseBody is the key, it "...indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name)." [Spring Reference Doc] LoginData is a simple POJO container for the JSON values from the client request, filled automatically if you put a jackson jar file (I use jackson-all-1.7.5.jar) into your classpath. As result of the controller method, I create a hashMap<String, String>. (e.g. with keys 'error' or 'view' and appropriate values). This map is then automatically serialized into JSON which is interpreted by the client (again normal html page incl. Javascript)
function checkResult(result)
{
if (result.error)
{
// do error handling
}
else
{
// use result.view
}
}
精彩评论