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

如果你现在已经有一个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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值