何时使用Session Bean

时间:2014-05-20 09:42:41

标签: java servlets ejb-3.0 session-bean

美好的一天,我对我的应用程序使用哪个会话bean感到困惑。我正在尝试构建像Facebook这样的移动网络应用程序,它可以同时允许多个用户。我在网上冲浪以获取更多信息。从我从堆栈溢出和其他教程收集的信息中,有状态会话bean在事务内部和事务之间(会话状态)维护状态,并且它意味着客户端。 Stateless不支持多个客户端来池化bean实例。虽然Singleton与无状态bean有点类似。

我的问题是我要将哪个会话bean用于该应用程序。感谢您的快速回复。

注意:客户端(移动电话)与servlet通信,servlet与EJB通信以从数据库中提取数据。

public class LoginServlet extends HttpServlet {

@EJB
CampusianDataBaseBeanLocal campusianDataBaseBean;

Campusian campusian;
Gson gson;


@Override
public void init() throws ServletException {
    super.init();
    campusian = new Campusian();
    gson = new Gson();
}


/**
 * Processes requests for both HTTP
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String username = request.getParameter("campusianUserName");
        String password = request.getParameter("campusianPassword");
        String gsonString;

        campusian.setUserName(username);
        campusian.setPassword(password);

        System.out.println("First time: "+username);

        /**
         * This check if the username and password entered by user is correct.
         * If yes set campusian setSuccess to true and convert the object to string using gson
         * Else set object campusian method to false
         */
        if (campusianDataBaseBean.login(campusian)) {
            campusian.setSuccess(true);
            System.out.println("Connected to the database");
            /**
            try {
                connection.connect();
                connection.login(username, password);
                if (connection.isAuthenticated()) {
                    System.out.println("Connected: "+connection.getServiceName());
                    campusian.setConnection(connection);
                    campusian.setSuccess(true);
                }else {
                    campusian.setSuccess(false);
                }
            } catch (XMPPException ex) {
                Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            **/
            gsonString = gson.toJson(campusian);
        }else {
            campusian.setSuccess(false);
            gsonString = gson.toJson(campusian);
        }

        //this sends the gson string to the mobile user
        out.print(gsonString);

    } finally {            
        out.close();
    }
}

}

1 个答案:

答案 0 :(得分:0)

对于所有不保留状态的类,您需要一个单独的bean。在您的情况下,对于数据库通信,您需要一个单例。

对于用户身份验证,通常将用户对象或用户令牌存储在会话本身的某个位置。根据您的实现,您将拥有某种SessionContext / SessionStore,其中维护登录状态。

您不需要会话范围的bean来维护用户会话!