java - 如何使用 JSON 在 JSP 和 Java Controller 之间进行交互?

标签 java javascript json rest

我试图理解 JSP(使用 JavaScript)和使用 JSON 的 Java Controller 之间的交互原理。例如,我有一个实体

public class Greeting {
    private final long id;
    private final String content;
    // other part omitted
}

和 Controller

@Controller
public class GreetingController {

    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/")
    public String redirect() {
        return "redirect:/greeting";
    }

    @RequestMapping(value = "/greeting")
    @ResponseBody
    public Greeting greeting(@RequestParam("name") String name) {
        return new Greeting(counter.incrementAndGet(), String.format("Hello, %s!", name));
    }
}

如何修改此代码以使用 JavaSctipt 向 Controller 发送 GET 请求并通过 JavaScript 在 jsp 页面上检索 JSON 答案?

如果我能提供一些示例:)或一些教程的链接,我将不胜感激。

最佳答案

您可以使用 jQuery 对 Controller 进行 ajax get 调用。请参阅https://api.jquery.com/jQuery.ajax/ 。您必须将输出类型指定为 JSON。

例如,

$.ajax({
        type: 'GET',
        url: '<Your URL>',
        cache: false,
        dataType: 'json',
                    // Your input parameters go here
        data: {name: 'someValue'},
        success: function(data, textStatus){                                
        },
        error: function(xhr, textStatus, errorThrown){
        }
    });

下面的链接解释了如何从 Controller 返回 JSON 对象: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

关于java - 如何使用 JSON 在 JSP 和 Java Controller 之间进行交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22717171/

相关文章:

java - 使用 Spring Boot 启动 tomcat 时出现 NotReadablePropertyException

javascript - KineticJS - 无法添加动态对象

javascript - r pkgdown docsearch algolia

javascript - ng-repeat 随机显示数据

java - 如何在Spring中从文件读取参数到Schedule注释?

java - 如何在 Eclipse 中运行 GWT 项目?

java - 初始化浮点值时出错

javascript - jQuery qTip 图像源相对路径

json - 在 Swift 中调用 JSONSerialization 时获取无效的 json

json - CXF 3.0 和 Spring - 未找到响应类的消息正文阅读器