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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35290692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:57:18  来源:igfitidea点击:

how to receive json response from spring controller to a jsp page

javajsonspringjspspring-mvc

提问by JPG

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 页面,其中包含一些文本字段。单击提交按钮时,它调用 Ajax 调用将数据发布到 Spring 控制器。现在将数据保存在数据库中后,控制器创建一个 JSON 响应。我希望此响应可用于 JSP 文件。下面是我的文件的代码...

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. But, I am unable see the alert box on jsp page i.e. "details added". How can I resolve this issue.

数据被保存在数据库中,因此 json 数据正在到达控制器方法。但是,我无法在 jsp 页面上看到警告框,即“已添加详细信息”。我该如何解决这个问题。

回答by Roman C

You need to add @ResponseBodyannotation

您需要添加@ResponseBody注释

@RequestMapping (value="addDb.htm", method=RequestMethod.POST)
@ResponseBody String  addEditCustomer(@RequestParam String jsonData)
{...}

You don't need to write JSON manually, Spring uses Hymanson library behind the scene to serialise objects to JSON. See Spring 3 MVC and JSON example

您不需要手动编写 JSON,Spring 在幕后使用 Hymanson 库将对象序列化为 JSON。请参阅Spring 3 MVC 和 JSON 示例

Add @ResponseBodyas return value. Wen Spring sees

  • Hymanson library is existed in the project classpath
  • The mvc:annotation-drivenis enabled
  • Return method annotated with @ResponseBody

Spring will handle the JSON conversion automatically.

添加@ResponseBody为返回值。文春见

  • Hymanson 库存在于项目类路径中
  • mvc:annotation-driven已启用
  • 带有注释的返回方法 @ResponseBody

Spring 将自动处理 JSON 转换。