Restlet实战(十三)如何在Servlet中呼叫Restlet
程序员文章站
2022-07-03 21:04:19
...
看到这个题目,或许你会问,你之前的很多文章不都是与servlet有关吗?这不是重复吗?
No,假设你现在正在用MVC的framework,如Struts,Spring MVC等来建造一个Web系统,但是当前需求要求你的代码能灵活的与另外的一个系统对接。那么你想到了使用Restlet来构建Restful web service。因此,你想在你的servlet里面使用restlet。
场景是这样,但是理解起来其实很简单,如果和在servlet里面使用restlet。
首先拷贝一份Restlet里面关于ServletConverer的API doc里面的说明的代码:
public class TestServlet extends HttpServlet {
private ServletConverter converter;
public void init() throws ServletException {
super.init();
this.converter = new ServletConverter(getServletContext());
Restlet trace = new Restlet(this.converter.getContext()) {
public void handle(Request req, Response res) {
getLogger().info("Hello World");
res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
}
};
this.converter.setTarget(trace);
}
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.converter.service(req, res);
}
}
上面代码还是比较简单的,无非需要做三步:
1. 实例化一个ServletConverter
this.converter = new ServletConverter(getServletContext());
2. 给第一步的ServletConverter实例设置一个restlet实例,这个实例在被调用时,执行restlet自己的代码
Restlet trace = new Restlet(this.converter.getContext()) {
public void handle(Request req, Response res) {
getLogger().info("Hello World");
res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
}
};
this.converter.setTarget(trace);
3.调用执行的方法
this.converter.service(req, res);
让我们打开源代码看一下上面的service方法:
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (getTarget() != null) {
Context.setCurrent(getContext());
// Convert the Servlet call to a Restlet call
final ServletCall servletCall = new ServletCall(request
.getLocalAddr(), request.getLocalPort(), request, response);
final HttpRequest httpRequest = toRequest(servletCall);
final HttpResponse httpResponse = new HttpResponse(servletCall,
httpRequest);
// Adjust the relative reference
httpRequest.getResourceRef().setBaseRef(getBaseRef(request));
// Adjust the root reference
httpRequest.setRootRef(getRootRef(request));
// Handle the request and commit the response
getTarget().handle(httpRequest, httpResponse);
commit(httpResponse);
} else {
getLogger().warning("Unable to find the Restlet target");
}
}
上面代码的注释,已经清楚的说明整个调用过程,不再分析。