restlet中是不提畅使用session的,所以restlet更适合做无状态的服务,如果象购物车这样的业务该怎么样呢,实际上restlet也不是完全不能
实现session,在API中有一个org.restlet.data.Cookie类,我们可以借助cookie来实现。
public class SessionTestResource extends Resource {
private ShopCart chart1 = null;
@Override
public void init(Context context, Request request, Response response) {
// TODO Auto-generated method stub
super.init(context, request, response);
String token = request.getCookies().getFirstValue("tsession");
if (token == null) {
chart1 = new ShopCart();
chart1.setToken("chart1");
token = chart1.getToken();
response.getCookieSettings().add(
new CookieSetting("tsession", token));
chart1.add();
centers.add(token, chart1);
} else {
chart1 = centers.getchart(token);
chart1.add();
}
}
public SessionTestResource() {
getVariants().add(new Variant(MediaType.TEXT_PLAIN));
}
public SessionTestResource(Context context, Request request,
Response response) {
super(context, request, response);
}
@Override
public Representation getRepresentation(Variant variant) {
String count=""+chart1.getCount();
Representation representation = new StringRepresentation(count,
MediaType.TEXT_PLAIN);
return representation;
}
}