[英]How to interact between JSP and Java controller using JSON?
I'm trying to understand principle of interaction between JSP (with JavaScript) and Java controller using JSON. 我试图了解JSP(使用JavaScript)和使用JSON的Java控制器之间的交互原理。 For example, I have an entity 例如,我有一个实体
public class Greeting {
private final long id;
private final String content;
// other part omitted
}
And 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));
}
}
How to modify this code to send GET request using JavaSctipt to controller and retrieve JSON answer by JavaScript on jsp page? 如何修改此代码以使用JavaSctipt向控制器发送GET请求并通过jsp页面上的JavaScript检索JSON答案?
I would be appreciated for some examples :) or for some tutorial's links. 对于某些示例,我将不胜感激:)或某些教程的链接。
You can use jQuery to make a ajax get call to the controller. 您可以使用jQuery对控制器进行ajax get调用。 See https://api.jquery.com/jQuery.ajax/ . 参见https://api.jquery.com/jQuery.ajax/ 。 You will have to specify the output type as JSON. 您将必须将输出类型指定为JSON。
eg, 例如,
$.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){
}
});
The below link explains how to return JSON object from controller: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/ 以下链接说明了如何从控制器返回JSON对象: http : //www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.