05 December 2016

EJB3: CRUD Select Insert Update Delete Search (EJB + Hibernate + JSP + Mysql) P2

Thêm sửa xóa search EJB Hibernate JSP Mysql
Tạo Entity
Tạo Session Bean TokenSessionBean
TokenSessionBean.java
Java EJB 2016
package session;

import dao.TokenDao;
import entity.Token;
import java.util.List;
import javax.ejb.Stateless;

/**
 *
 * @author Lonely
 */
@Stateless
public class TokenSessionBean implements TokenSessionBeanLocal {

    //Alt + Insert > Add Business Method..
//    @Override
//    public Token getToken(String token) {
//        TokenDao dao = new TokenDao();
//        return dao.getToken(token);
//    }
//Alt + Insert > Add Business Method.. @Override public List<Token> getAll() { TokenDao dao = new TokenDao(); return dao.getAll(); }
//Alt + Insert > Add Business Method.. @Override public List<Token> searchToken(String tokenString) { TokenDao dao = new TokenDao(); return dao.searchToken(tokenString); } //Alt + Insert > Add Business Method.. @Override public boolean insert(String tokenStringInsert, int userIdInsert) { TokenDao dao = new TokenDao(); return dao.insertToken(tokenStringInsert, userIdInsert); } //Alt + Insert > Add Business Method.. @Override public boolean update(String tokenString, int userId) { TokenDao dao = new TokenDao(); return dao.updateToken(tokenString, userId); } //Alt + Insert > Add Business Method.. @Override public boolean delete(int userId) { TokenDao dao = new TokenDao(); return dao.deleteToken(userId); } } 
TokenDao.java
Java EJB 2016
package dao;

import entity.Token;
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 TokenDao {

    public boolean insertToken(String tokenStringInsert, int userIdInsert) {
        try {
            Session session = NewHibernateUtil.getSessionAndBeginTransaction();
            Token tk = new Token();
            tk.setUserId(userIdInsert);
            tk.setTokenString(tokenStringInsert);
            session.persist(tk); //Insert
            NewHibernateUtil.commitCurrentSessions();
            return true;
        } catch (Exception ex) {
            Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                NewHibernateUtil.commitCurrentSessions();
            } catch (Exception ex) {
                Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    NewHibernateUtil.closeCurrentSessions();
                } catch (Exception ex) {
                    Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return false;
    }

    public boolean updateToken(String tokenString, int userId) {
        try {
            Session session = NewHibernateUtil.getSessionAndBeginTransaction();
            String hql = "UPDATE Token SET tokenString = :tokenString WHERE userId = :userId";
            Query query = session.createQuery(hql);
            query.setParameter("userId", userId);
            query.setParameter("tokenString", tokenString);

            query.executeUpdate(); //Update
            NewHibernateUtil.commitCurrentSessions();
            return true;
        } catch (Exception ex) {
            NewHibernateUtil.rollBackCurrentSessions();
        } finally {
            try {
                NewHibernateUtil.commitCurrentSessions();
            } catch (Exception ex) {
                Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    NewHibernateUtil.closeCurrentSessions();
                } catch (Exception ex) {
                    Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return false;
    }

//    public Token getToken(String token) {
//        Session session = NewHibernateUtil.getSessionAndBeginTransaction();
//        try {
//            String hql = "SELECT t FROM Token t WHERE t.tokenString = :tokenString";
//            Query query = session.createQuery(hql);
//            query.setParameter("tokenString", token);
//            
//            return (Token) query.uniqueResult();
//        } catch (Exception e) {
//            NewHibernateUtil.rollBackCurrentSessions();
//        } finally {
//            try {
//                NewHibernateUtil.commitCurrentSessions();
//            } catch (Exception ex) {
//                Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
//            } finally {
//                try {
//                    NewHibernateUtil.closeCurrentSessions();
//                } catch (Exception ex) {
//                    Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        }
//        return null;
//    }

    public List<Token> getAll() {
        Session session = NewHibernateUtil.getSessionAndBeginTransaction();
        try {
            String hql = "SELECT t FROM Token t";
            Query query = session.createQuery(hql);
            
            return query.list();
        } catch (Exception e) {
            NewHibernateUtil.rollBackCurrentSessions();
        } finally {
            try {
                NewHibernateUtil.commitCurrentSessions();
            } catch (Exception ex) {
                Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    NewHibernateUtil.closeCurrentSessions();
                } catch (Exception ex) {
                    Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }

    public boolean deleteToken(int userId) {
        try {
            Session session = NewHibernateUtil.getSessionAndBeginTransaction();
            String hql = "DELETE FROM Token WHERE userId = :userId";
            Query query = session.createQuery(hql);
            query.setParameter("userId", userId);

            query.executeUpdate(); //Delete
            NewHibernateUtil.commitCurrentSessions();
            return true;
        } catch (Exception ex) {
            NewHibernateUtil.rollBackCurrentSessions();
        } finally {
            try {
                NewHibernateUtil.commitCurrentSessions();
            } catch (Exception ex) {
                Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    NewHibernateUtil.closeCurrentSessions();
                } catch (Exception ex) {
                    Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return false;
    }
    
     public List<Token> searchToken(String tokenString) {
        Session session = NewHibernateUtil.getSessionAndBeginTransaction();
        try {
            String hql = "SELECT t FROM Token t Where t.tokenString LIKE :tokenString";
            Query query = session.createQuery(hql);
            query.setParameter("tokenString", "%"+tokenString+"%");
            
            return query.list(); //Get list
        } catch (Exception e) {
            NewHibernateUtil.rollBackCurrentSessions();
        } finally {
            try {
                NewHibernateUtil.commitCurrentSessions();
            } catch (Exception ex) {
                Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    NewHibernateUtil.closeCurrentSessions();
                } catch (Exception ex) {
                    Logger.getLogger(TokenDao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }    
   
}
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>
        <c:if test="${not empty items}">
            <table border="1">
                <tr>
                    <th>UserId</th>
                    <th>TokenString</th>
                    <th colspan="2"> <a href="insert.jsp"><input type="button" value="Insert" /></a> </th>
                </tr>
                <!--Update - Delete-->
                <c:forEach items="${items}" var="it">
                    <form method="POST" action="CUDServlet">
                        <tr>
                            <td><input type="text" name="userId" value="${it.userId}" /></td>
                            <td><input type="text" name="tokenString" value="${it.tokenString}" /> </td>
                            <td> <input type="submit" value="Update" name="action"/></td>
                            <td> <input type="submit" value="Delete" name="action" /></td>
                        </tr>
                    </form>
                </c:forEach>
                <!--Insert-->
                <td colspan="4">
                    <form action="CUDServlet">
                        <input type="text" name="searchToken" value="${it.tokenString}" size="55"/>
                        <input type="submit" value="Search"/>
                    </form>
                </td>
            </table>
        </c:if>
    </body>
</html>
insert.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>

        <form method="POST" action="CUDServlet">
            <td><input type="text" name="userId" /> </td>
            <td><input type="text" name="tokenString"  /> </td>
            <td colspan="2"> <input type="submit" value="Insert" name="action"/></td>
        </form>
    </body>
</html>
Tạo servlet CUDServlet
CUDServlet.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 session.TokenSessionBeanLocal;

/**
 *
 * @author Lonely
 */
public class CUDServlet extends HttpServlet {

    //Alt + Insert > Call Enterpride Bean..
    @EJB
    private TokenSessionBeanLocal tokenSessionBean;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Action name
        String button = request.getParameter("action");

        //Input name
        int userId = Integer.parseInt(request.getParameter("userId"));
        String tokenString = request.getParameter("tokenString");

        //Case button submit
        if ("Insert".equalsIgnoreCase(button)) {
            if (tokenSessionBean.insert(tokenString, userId)) {
                request.setAttribute("items", tokenSessionBean.getAll());
                request.getRequestDispatcher("tokenview.jsp").forward(request, response);
            } else {
                request.setAttribute("ERROR", "Insert error!");
                request.getRequestDispatcher("tokenview.jsp").forward(request, response);
            }
        } else if ("Update".equalsIgnoreCase(button)) {
            if (tokenSessionBean.update(tokenString, userId)) {
                request.setAttribute("items", tokenSessionBean.getAll());
                request.getRequestDispatcher("tokenview.jsp").forward(request, response);
            } else {
                request.setAttribute("ERROR", "Update error!");
                request.getRequestDispatcher("tokenview.jsp").forward(request, response);
            }
        } else if ("Delete".equalsIgnoreCase(button)) {
            if (tokenSessionBean.delete(userId)) {
                request.setAttribute("items", tokenSessionBean.getAll());
                request.getRequestDispatcher("tokenview.jsp").forward(request, response);
            } else {
                request.setAttribute("ERROR", "Delete error!");
                request.getRequestDispatcher("tokenview.jsp").forward(request, response);
            }
        } else {
           
            request.setAttribute("items", tokenSessionBean.getAll());
            request.getRequestDispatcher("tokenview.jsp").forward(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String searchToken = request.getParameter("searchToken");
        //Search tokenString
        if (tokenSessionBean.searchToken(searchToken) != null) {
            request.setAttribute("items", tokenSessionBean.searchToken(searchToken) );
            request.getRequestDispatcher("tokenview.jsp").forward(request, response);
        } else {
            request.setAttribute("ERROR", "Search error!");
            request.getRequestDispatcher("tokenview.jsp").forward(request, response);
        }
    }

}
Cấu hình web.xml trang hiển thị đầu tiên là login.jsp
Các bạn cấu hình thêm cho LoginServlet để hiển thị List
 Cấu hình mapping đến class Entity
Tất cả đã hoàn thiện!
Bấm vào hình tam giác và Clear and build > Deploy > Run test

Dowload zip (Import NetBeans)
<< Back Phần 1

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang