【问题标题】:Calling Java code from JavaScript (Spring boot)从 JavaScript 调用 Java 代码(Spring 引导)
【发布时间】:2017-12-21 15:19:57
【问题描述】:
这是我的控制器:
@Controller
@RequestMapping("/test")
public class TestServlet {
@RequestMapping("/country/{latitude}-{longitude}")
public String getCountry(@PathVariable String latitude, @PathVariable String longitude, Model model){
//inject the data in the JSP
model.addAttribute("latitude", latitude);
model.addAttribute("longitude", longitude);
//return the html
return "private/private";
}
我想知道如何使用 javascript 代码中的参数访问此方法。
public String getCountry(@PathVariable String latitude, @PathVariable String longitude, Model model);
【问题讨论】:
标签:
javascript
java
url
spring-boot
【解决方案1】:
这样就可以了
$.ajax({
type : "GET",
url : "http://<server>:<port>/test/country/<latitudevalue>-<longitudevalue>",
contentType: "application/json",
dataType: "json",
success : function (data, status) {
......
},
error : function (status) {
....
}
});
【解决方案2】:
我担心 @PathVariable 在正确识别由 '-' 分割的变量时会出现一些问题。
我会为此任务使用其他标准字符,例如 '/' 或 '&'。
我还会在 @RequestMapping 注释中指定 HTTP 方法,例如:
@RequestMapping(value = "/country/{latitude}-{longitude}", method = RequestMethod.GET)
js ajax 调用类似于:
$.ajax({
type : "GET",
contentType: "application/json",
dataType: "json",
url : "/test/country/" + lat + "-" + lon,
success : function (data, status) {
/*CODE*/
},
});
【解决方案3】:
如果你想得到 JSON 格式的结果,那么你可以改变控制器如下,
@Controller
@RequestMapping("/test")
public class TestServlet {
@ResponseBody
@RequestMapping("/country", method = RequestMethod.GET, produces = "application/json")
public Map<String, String> getCountry(@PathVariable String latitude, @PathVariable
String longitude){
final Map<String, String> messageObject = new HashMap<>();
messageObject.put("latitude", latitude);
messageObject.put("longitude", longitude);
//return the html
return messageObject;
}
然后在客户端,
$.getJSON("/country", {latitude: <latitude>, longitude: <longitude>}, function(data) {
if (data != null) {
for(key in data){
var lat = data[latitude];
var long = data[longitude];
}
}
});