在前端用JavaScript AJAX直接调用Restlet框架写的一个REST接口时,遇到了传说中的AJAX跨域问题。
百度谷歌了很久,看到了很多人把JavaScript的dataType改成jsonp以规避这个问题(参考:http://www.cnblogs.com/sunxucool/p/3433992.html),然而,这样处理会增加JavaScript的调用复杂度,不利于项目代码的维护。
在查看Restlet官方文档后,发现其框架中已加入了CorsService来解决AJAX跨域问题。
更新至Restlet 2.3.7版本,在main方法中加入CorsService设置,具体如下:
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8082);
component.getServers().getContext().getParameters().add("maxThreads", "512");
// 解决AJAX跨域问题
CorsService cors = new CorsService();
cors.setAllowedOrigins(new HashSet(Arrays.asList("*")));
cors.setAllowedCredentials(true);
component.getServices().add(cors);
// 增加Applications
component.getDefaultHost().attach("/api", new PathApplication());
// 启动
component.start();
重启REST服务,重新进行AJAX请求数据,顺利获取到,问题解决!