如何通过 Spring MVC 提供 Java 模型的 RDF 表示?
我有使用 Spring 内容协商机制工作的 JSON 和 XML 表示,并且希望对 RDF 执行相同的操作。
最佳答案
假设您正在为 MVC 应用程序使用注释驱动配置,这实际上可能非常简单。使用 W3C 的 Media Types Issues for Text RDF Formats作为内容类型规范的指南,增强现有解决方案非常容易。真正的问题是,当发出 RDF 请求时,您想要的序列化类型是什么?如果我们利用 Jena 作为底层模型技术,那么支持任何标准序列化都是微不足道的。 Json 是唯一给我带来一点困难的,但你已经解决了。
正如您所看到的,序列化的实现(使用标准 Jena,并且没有额外的库)实际上非常容易做到!问题最终只是将正确的序列化与提供的内容类型相匹配。
编辑 2014 年 4 月 19 日
以前的内容类型来自捕获工作组讨论的文档。该帖子已被编辑以反射(reflect) IANA Media Type registry 的内容类型。补充了RDF1.1 N-Triples和 JSON-LD标准。
@Controller
public class SpecialController
{
public Model model = null; // set externally
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"application/x-javascript", "application/json", "application/ld+json"})
public @ResponseBody String getModelAsJson() {
// Your existing json response
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"application/xml", "application/rdf+xml"})
public @ResponseBody String getModelAsXml() {
// Note that we added "application/rdf+xml" as one of the supported types
// for this method. Otherwise, we utilize your existing xml serialization
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"application/n-triples"})
public @ResponseBody String getModelAsNTriples() {
// New method to serialize to n-triple
try( final ByteArrayOutputStream os = new ByteArrayOutputStream() ){
model.write(os, "N-TRIPLE");
return os.toString();
}
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"text/turtle"})
public @ResponseBody String getModelAsTurtle() {
// New method to serialize to turtle
try( final ByteArrayOutputStream os = new ByteArrayOutputStream() ){
model.write(os, "TURTLE");
return os.toString();
}
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"text/n3"})
public @ResponseBody String getModelAsN3() {
// New method to serialize to N3
try( final ByteArrayOutputStream os = new ByteArrayOutputStream() ){
model.write(os, "N3");
return os.toString();
}
}
}
关于java - 使用 Spring MVC 提供 Java 模型的 RDF 表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17313801/