有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript如何使用JSON在JSP和Java控制器之间进行交互?

我试图理解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应答

我将感谢一些例子:)或一些教程的链接


共 (1) 个答案

  1. # 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/