how to receive json response from spring controller to a jsp page
You need to add @ResponseBody
annotation
@RequestMapping (value="addDb.htm", method=RequestMethod.POST)
@ResponseBody String addEditCustomer(@RequestParam String jsonData)
{...}
You don't need to write JSON manually, Spring uses Jackson library behind the scene to serialise objects to JSON. See Spring 3 MVC and JSON example
Add
@ResponseBody
as return value. Wen Spring sees
- Jackson library is existed in the project classpath
- The
mvc:annotation-driven
is enabled- Return method annotated with
@ResponseBody
Spring will handle the JSON conversion automatically.
Comments
-
JPG almost 2 years
I have created one JSP page, with some some text fields. On click of submit button, it calls Ajax call to post the data to Spring controller. Now after saving the data in database, controller creates a JSON response. I want this response to be available on JSP file. below are the code of my files...
JSP file:
$(document).ready(function(){ $("#submitButton").click(function(e){ var formData = getFormData(); $.ajax({ type: 'POST', 'url': 'http://localhost:8080/Test_ReportingUI/addDb.htm', data: {jsonData: JSON.stringify(formData)}, dataType: 'json', success: function(response){ try{ var strResponse=jQuery.parseJSON(response); }catch(err){} if(response.status=='ok') { alert("details added"); } else { alert("error happened"); } }, timeout: 10000, error: function(xhr, status, err){ if(status=='timeout') { alert('Request time has been out',''); } console.log(status,err); } }); }); });
spring controller method:
@Autowired RWCustomerService rwCustomerService; @RequestMapping (value="addDb.htm", method=RequestMethod.POST) String addEditCustomer(@RequestParam String jsonData) { System.out.println("hello world"); System.out.println("-----------------\n"+jsonData); ModelAndView modelAndView=new ModelAndView("custDB_setup"); JSONObject jsonResponse = new JSONObject(); try{ JSONObject requestedJSONObject = new JSONObject(jsonData); String dbName = requestedJSONObject.getString("dbName"); String dbUserName = requestedJSONObject.getString("dbUserName"); String dbPassword = requestedJSONObject.getString("dbPassword"); Iterator it=requestedJSONObject.keys(); while(it.hasNext()){ System.out.println("Oo..: "+it.next()); } RWReportCustomerDB rwReportCustomerDB = new RWReportCustomerDB(); rwReportCustomerDB.setDbName(dbName); rwReportCustomerDB.setDbLogin(dbUserName); rwReportCustomerDB.setDbPassword(dbPassword); rwCustomerService.saveDb(rwReportCustomerDB); jsonResponse.put("status", "ok"); } catch(Exception ex){ ex.printStackTrace(); } return jsonResponse.toString(); }
data is getting saved in database, therefore json data is reaching the controller method. But, I am unable see the alert box on jsp page i.e. "details added". How can I resolve this issue.