欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Restlet实战(十四)如何在Restlet得到Servlet request和Session

程序员文章站 2022-07-03 21:04:43
...

如果你现在已经有一个web系统,而为了一些需求,你集成了restlet来提供Restful web service,那么如何在restlet里面获取放到HttpServletRequest和Session里面的值呢?

 

可以利用ServletCall类来达到目的,我们可以在Resource的init方法里面加入一些代码:

 

@Override
public void init(Context context, Request request, Response response) {
	super.init(context, request, response);

	if(request instanceof HttpRequest){
		HttpServletRequest hsr = ServletCall.getRequest(request);
		
		Enumeration params = hsr.getParameterNames();
		
		HttpSession session = hsr.getSession();
		if(session != null){
			String sessFlag = (String)sess.getAttribute("sessFlag");
		}
		
		String address = hsr.getParameter("address");
	}
}

 

 

同时给出ServletCall的getRequest方法的源代码,以便于加深理解:

 

public static HttpServletRequest getRequest(Request request) {
	HttpServletRequest result = null;

	if (request instanceof HttpRequest) {
		final HttpCall httpCall = ((HttpRequest) request).getHttpCall();

		if (httpCall instanceof ServletCall) {
			result = ((ServletCall) httpCall).getRequest();
		}
	}

	return result;
}

 

最后,我想说的是,使用Restlet和Servlet交互,只是假设你已经有一个web系统,或者说,你已经在这个系统上投资很多,否则,完全可以基于Restlet构建一个新的系统。看看Restlet的开发者Rhett Sutphin 在论坛对一个提问者的解答关于集成Servlet问题中提到的:

 

>
> My Questions:
> 1. What is the best way to integrate my servlet with the RESTLETs?
>
> 2. Is there a way for me to pass java objects from the restlet to the
> servlet? This way in the servlet I can extract java objects and not 
> rely on
> re-assembling the JSON or XML contained in the Response 
> Representation?

For a new application (and assuming I understand what you're trying to 
do), I'd suggest using content negotation in Restlet and not using 
Servlet/JSP at all.

If you really don't want to do that, or if you already have a large 
investment in JSP-based views, I'd extract the business logic into a 
separate layer and make it available to both your servlets and your 
restlets.