简体   繁体   English

如何从spring控制器接收jsp页面的json响应

[英]how to receive json response from spring controller to a jsp page

I have created one JSP page, with some some text fields. 我创建了一个JSP页面,其中包含一些文本字段。 On click of submit button, it calls Ajax call to post the data to Spring controller. 单击提交按钮后,它将调用Ajax调用以将数据发布到Spring控制器。 Now after saving the data in database, controller creates a JSON response. 现在,将数据保存到数据库中后,控制器将创建一个JSON响应。 I want this response to be available on JSP file. 我希望此响应在JSP文件上可用。 below are the code of my files... 以下是我文件的代码...

JSP file: JSP文件:

$(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. 数据已保存在数据库中,因此json数据已到达控制器方法。 But, I am unable see the alert box on jsp page ie "details added". 但是,我无法在jsp页面上看到警报框,即“添加了详细信息”。 How can I resolve this issue. 我该如何解决此问题。

You need to add @ResponseBody annotation 您需要添加@ResponseBody批注

@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. 您不需要手动编写JSON,Spring会在后台使用Jackson库将对象序列化为JSON。 See Spring 3 MVC and JSON example 请参阅Spring 3 MVC和JSON示例

Add @ResponseBody as return value. 添加@ResponseBody作为返回值。 Wen Spring sees 温春看到

  • Jackson library is existed in the project classpath Jackson库存在于项目类路径中
  • The mvc:annotation-driven is enabled 启用了mvc:annotation-driven
  • Return method annotated with @ResponseBody @ResponseBody注释的返回方法

Spring will handle the JSON conversion automatically. Spring将自动处理JSON转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM