对于某些背景,我正在使用JBoss AS 7和EJB。我正在使用errai消息总线从客户端向我的服务器发送消息,当它最初连接时检索其会话ID,以便稍后我可以从它发出请求并让服务器响应特定客户端。
我该怎么做呢?我可以以某种方式注入HttpSession对象服务器端吗?我对此很新,所以请耐心等待。如果我太模糊,请告诉我,我会尝试详细说明。
答案 0 :(得分:0)
// the following variable is in the Http servlet service() method arguments
// only shown here this way to demonstrate the process
javax.servlet.http.HttpServletRequest serviceRequest;
javax.servlet.http.HttpServletResponse serviceResp; // addCookie()
javax.servlet.http.HttpSession cecil;
javax.servlet.http.Cookie[] reqCk;
// "(boolean overload) "true" creates the session" or call the other overload version method with no argument
// to retrieve the session getSession() "the server container stores and creates sessions"
// false in that version is to avoid bothering for a session to cut down uneeded processing
cecil = serviceRequest.getSession();//creates a session if it does not have one
String httpSession_ID = cecil.getID();
if((reqCk = serviceRequest.getCookies()) == null){
// perhaps create a cookie here using "new class "
// cookiePiece = new javax.servlet.http.Cookie("COOKIENAME",....); ....YOU MUST LEARN THE COOKIE PARTS WRITING RULES FOR BROWSER COOKIES !!! ; ; ;
serviceResp.addCookie(cookiePiece); // now is on the servers array "reqCk"
}else{
// process the cookie here using javax.servlet.http.Cookie methods
}
存储和检索数据的其他方式是会话范围的JSP或JSF bean 。
答案 1 :(得分:0)
如果要向ErraiBus服务方法发送消息,则可以使用Message
对象。您可以从中检索会话并获取该会话的ID,如下所示:
@Service
public class ClientHelloService implements MessageCallback {
@Override
public void callback(final Message message) {
HttpSession session = message.getResource(
HttpServletRequest.class, HttpServletRequest.class.getName()).getSession();
System.out.println("Client said hello. Session ID: " + session.getId());
}
}
如果您将消息发送到Errai RPC端点,则无法轻松访问该消息。在这种情况下,您必须使用RpcContext.getSession()
方法:
@Service
public class ClientHelloRpcServiceImpl implements ClientHelloRpcService {
@Override
public void hello() {
HttpSession session = RpcContext.getHttpSession();
System.out.println("Client said hello. Session ID: " + session.getId());
}
}
这种方式很简单但很难看:RpcContext类在ThreadLocal中存储包含RPC请求的Message对象,它只是从中检索HttpSession。