05 December 2016

EJB3: Login (EJB + Hibernate + JSP + Mysql) P1

Check Login EJB với Hibernate server GlassFish
Tạo Database
CREATE DATABASE `ejb` /*!40100 DEFAULT CHARACTER SET utf8 */;

CREATE TABLE `token` (
  `UserId` int(11) NOT NULL,
  `TokenString` varchar(45) DEFAULT NULL,
  `CreateDate` date DEFAULT NULL,
  PRIMARY KEY (`UserId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user` (
  `username` varchar(45) NOT NULL,
  `password` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Tạo project có tên CRUD_EJB_Hibernate_Jsp

Cấu trúc mới của project
Add library: Hibernate 4.3.X

Add connector jdbc: mysql-connector-java-5.1.39-bin
Các bạn tạo package: util
và tạo class có tên NewHibernateUtil.java
NewHibernateUtil.java
Java EJB 2016
package util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            String hibernate_cfg_path = "hibernate.cfg.xml";
            Configuration configuration = new Configuration().configure(hibernate_cfg_path);
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public static Session getSessionAndBeginTransaction() {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        return session;
    }

    public static Session commitCurrentSessions() throws Exception {
        Session session = sessionFactory.getCurrentSession();
        if (session.isOpen()) {
            Transaction t = session.getTransaction();
            if (t.isActive()) {
                try {
                    t.commit();
                } catch (Throwable ex) {
                    return session;
                }
            } else {
                return session;
            }
        }
        return null;
    }

    public static void rollBackCurrentSessions() {
        rollBackSessions(sessionFactory.getCurrentSession());
    }

    public static void rollBackSessions(Session session) {
        if (session != null) {
            if (session.isOpen()) {
                Transaction t = session.getTransaction();
                try {
                    t.rollback();
                } catch (Exception ex) {
                    ex.printStackTrace();
                } catch (Throwable ta) {

                } finally {
                    if (session.isOpen()) {
                        session.close();
                    }
                }
            }
        }
    }

    public static void closeCurrentSessions() throws Exception {
        Session session = sessionFactory.getCurrentSession();
        if (session != null) {
            try {
                if (session.isOpen()) {
                    session.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Chúng ta tạo Entity Classes from Database
Ở phần này nếu các bạn chưa tạo Data Source thì có thế tạo như sau: vào đây
 Finish
Chúng ta tạo Session Bean để thực hiện tạo các Business method
Alt + Insert > Add Business Method ..

Chúng ta tạo class UserDao + tạo mới package dao
UserDao.java
Java EJB 2016
package dao;

import entity.User;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import util.NewHibernateUtil;

/**
 *
 * @author Lonely
 */
public class UserDao {
    public boolean checkLogin(String username, String password) {
        Session session = NewHibernateUtil.getSessionAndBeginTransaction();
        try {
            String sql = "SELECT u from User u where u.username=:username and u.password=:password";
            Query query = session.createQuery(sql);
            query.setParameter("username", username);
            query.setParameter("password", password);
            List<User> list = query.list();
            if (list.size() == 1 ) {
                session.close();
                return true;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                NewHibernateUtil.commitCurrentSessions();
            } catch (Exception ex) {
                Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    NewHibernateUtil.closeCurrentSessions();
                } catch (Exception ex) {
                    Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return false;
    }
}

UserSessionBean.java
Java EJB 2016
package session;

import dao.UserDao;
import javax.ejb.Stateless;

/**
 *
 * @author Lonely
 */
@Stateless
public class UserSessionBean implements UserSessionBeanLocal {

    @Override
    public boolean login(String username, String password) {
        UserDao u = new UserDao();
        return u.checkLogin(username, password);
    }

}
Tạo file xml tên: hibernate.cfg
hibernate.cfg.xml
Java EJB 2016
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ejb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1234567</property>
        
        <property name="current_session_context_class">thread</property>
    
        <property name="show_sql">false</property>
        <property name="format_sql">true</property>
        
        <!-- Quan tri he thong -->
        <mapping class="entity.User"/>
    </session-factory>
</hibernate-configuration>

login.jsp
Java EJB 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Login !</h1>
        <form action="LoginServlet" method="POST">
            Username:<input type="text" name="username" /><br/>
            Password:<input type="password" name="password" /><br/>
            <input type="submit" value="Login" />
        </form>
    </body>
</html>

Tạo Servlet

LoginServlet.java
Java EJB 2016
package servlet;

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.TokenSessionBeanLocal;
import session.UserSessionBeanLocal;

/**
 *
 * @author Lonely
 */
public class LoginServlet extends HttpServlet {
    //Alt + Call Enterpride Bean
    @EJB
    private UserSessionBeanLocal userSessionBean;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Logout
        request.getSession().invalidate();
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Login
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //Boolean login Session Bean
        if (userSessionBean.login(username, password)) {
            HttpSession session = request.getSession();
            session.setAttribute("welcome", username);
           
            request.getRequestDispatcher("tokenview.jsp").forward(request, response);
        }else{
            request.setAttribute("ERROR", "Login invalid!");
            request.getRequestDispatcher("tokenview.jsp").forward(request, response);
        }
    }
}
tokenview.jsp
Java EJB 2016
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
    <c:choose>
        <c:when test="${not empty welcome}">
            Welcome:<font color="red"> ${sessionScope.welcome}</font>
            <a href="LoginServlet"><input type="button" value="Logout" /></a>
        </c:when>
        <c:otherwise>
            <a href="login.jsp"><input type="button" value="Login" /></a>
        </c:otherwise>
    </c:choose>

    <c:if test="${not empty ERROR}">
        ${requestScope.ERROR}
    </c:if>
</body>
</html>
Clear and build >  Deploy > Run test
http://localhost:8080/CRUD_EJB_Hibernate_Jsp-war/login.jsp


Note: Nhắc nhở một số lỗi thường gặp
Lỗi không Deploy được:
Lỗi mapping class ở file hibernate.cfg.xml


Lỗi thiếu jdbc connector mysql-connector-java-5.1.39-bin



0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang