【问题标题】:How to interact between JSP and Java controller using JSON?如何使用 JSON 在 JSP 和 Java 控制器之间进行交互?
【发布时间】:2014-03-28 15:36:11
【问题描述】:

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

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

和控制器

@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 向控制器发送 GET 请求并在 jsp 页面上通过 JavaScript 检索 JSON 答案?

我将不胜感激一些例子:) 或一些教程的链接。

【问题讨论】:

  • 您可以/可以使用哪些 JavaScript 框架?
  • 我觉得jQuery会很好

标签: java javascript json rest


【解决方案1】:

您可以使用 jQuery 对控制器进行 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){
        }
    });

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2016-04-24
    • 1970-01-01
    相关资源
    最近更新 更多