06 December 2016

EJB3: Login vs Show data template Admin Lab (EJB + Persistence + JSF+ Mysql) P1

Check Login EJB với JPA server GlassFish 4.0

Database mysql workbench
CREATE DATABASE `ejb` /*!40100 DEFAULT CHARACTER SET utf8 */;

CREATE TABLE `user` (
  `username` varchar(25) NOT NULL,
  `password` varchar(25) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Tạo mới project EJB
Tạo project có tên: EnterpriseApplicationJSF
 Tôi chọn GlassFish 4.0
Dưới đây là project vừa mới tạo xong
 Tiếp theo Download template Login+Table tôi đã chuẩn bị sẵn. Vui lòng giải nén và coppy vào Web Pages
 Fix hết các lỗi đỏ thông báo.
Add project JavaServer Faces
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


User.java
Java EJB 2016
package entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Lonely
 */
@Entity
@Table(name = "user")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
    @NamedQuery(name = "User.findByUsername", query = "SELECT u FROM User u WHERE u.username = :username"),
    @NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password")})
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "username")
    private String username;
    @Size(max = 45)
    @Column(name = "password")
    private String password;

    public User() {
    }

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (username != null ? username.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof User)) {
            return false;
        }
        User other = (User) object;
        if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.User[ username=" + username + " ]";
    }
    
}
Tạo Session Bean
Finish
Add Business Method checkLogin

Add method checkLogin
Add method findAll

Add Use Entity Manager
UserSessionBean.java
Java EJB 2016
package session;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

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

    //Alt + Insert > Use Entity Manager
    @PersistenceContext(unitName = "EnterpriseApplicationJSF-ejbPU")
    private EntityManager em;

    //Alt+Insert > Add Business Method..
    @Override
    public boolean checkLogin(String username, String password) {
        //2. Tao query intances
        String jpql = "Select u From User u Where u.username=:username and u.password=:password";
        Query query = em.createQuery(jpql);
        query.setParameter("username", username);
        query.setParameter("password", password);
        //3. Truy van vao object
        try {
            query.getSingleResult();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
// Alt+ Insert > Add Business Method.. @Override public List<User> findAll() { String jpql = "SELECT u FROM User u"; Query query = em.createQuery(jpql); return query.getResultList(); } public void persist(Object object) { em.persist(object); } }
Add library connector jdbc
Tạo Manager Bean cho JSF (gần giống servlet của jsp)
UserJSFManagedBean.java
Java EJB 2016
package controller;

import java.io.IOException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import session.UserSessionBeanLocal;

/**
 *
 * @author Lonely
 */
@Named(value = "userJSFManagedBean")
@SessionScoped
public class UserJSFManagedBean implements Serializable {

    //Alt + Call Enterpride Bean..
    @EJB
    private UserSessionBeanLocal userSessionBean;

    private String username;
    private String password;
    private List<User> list;

    //Tao setter + getter List

    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }
    //Tao setter + getter User
    public UserSessionBeanLocal getUserSessionBean() {
        return userSessionBean;
    }

    public void setUserSessionBean(UserSessionBeanLocal userSessionBean) {
        this.userSessionBean = userSessionBean;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    //Tao method login kieu String
    public String login() {
        if (userSessionBean.checkLogin(username, password)) {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
            session.setAttribute("user", username);
            list = userSessionBean.findAll();
            return "show"; //Di chuyen den trang show.xhtml
        } else {
            FacesContext fc = FacesContext.getCurrentInstance();
            fc.addMessage(null, new FacesMessage("Sai username hoặc password!"));
            return "404"; //Invalid di chuyen den trang 404.xhtml
        }
    }

    //Tao method logout kieu void
    public void logout() throws IOException {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ec.invalidateSession();
        ec.redirect(ec.getRequestContextPath() + "/faces/login.xhtml");
    }

    public UserJSFManagedBean() {
    }

}
Cấu hình lại trang show.xhtml như sau:
show.xhtml
Java EJB 2016
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <meta charset="utf-8" />
        <title>Data Tables</title>
        <meta content="width=device-width, initial-scale=1.0" name="viewport" />
        <meta content="" name="description" />
        <meta content="" name="author" />
        <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
        <link href="assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
        <link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
        <link href="css/style.css" rel="stylesheet" />
        <link href="css/style_responsive.css" rel="stylesheet" />
        <link href="css/style_default.css" rel="stylesheet" id="style_color" />

        <link href="assets/fancybox/source/jquery.fancybox.css" rel="stylesheet" />
        <link rel="stylesheet" type="text/css" href="assets/uniform/css/uniform.default.css" />
    </h:head>

    <!-- END HEAD -->
    <!-- BEGIN BODY -->
    <h:body class="fixed-top">
        <!-- BEGIN HEADER -->
        <div id="header" class="navbar navbar-inverse navbar-fixed-top">
            <!-- BEGIN TOP NAVIGATION BAR -->
            <div class="navbar-inner">
                <div class="container-fluid">
                    <!-- BEGIN LOGO -->
                    <a class="brand" href="show.xhtml">
                        <img src="img/logo.png" alt="Admin Lab" />
                    </a>
                    <!-- END LOGO -->
                    <!-- BEGIN RESPONSIVE MENU TOGGLER -->
                    <a class="btn btn-navbar collapsed" id="main_menu_trigger" data-toggle="collapse" data-target=".nav-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="arrow"></span>
                    </a>
                    <!-- END RESPONSIVE MENU TOGGLER -->
                    <div id="top_menu" class="nav notify-row">
                        <!-- BEGIN NOTIFICATION -->
                        <ul class="nav top-menu">
                            <!-- BEGIN SETTINGS -->
                            <li class="dropdown">
                                <a class="dropdown-toggle element" data-placement="bottom" data-toggle="tooltip" href="#" data-original-title="Settings">
                                    <i class="icon-cog"></i>
                                </a>
                            </li>
                            <!-- END SETTINGS -->
                            <!-- BEGIN INBOX DROPDOWN -->
                            <li class="dropdown" id="header_inbox_bar">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                    <i class="icon-envelope-alt"></i>
                                    <span class="badge badge-important">1</span>
                                </a>
                                <ul class="dropdown-menu extended inbox">
                                    <li>
                                        <p>You have 1 new messages</p>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="photo"><img src="./img/avatar-mini.png" alt="avatar" /></span>
                                            <span class="subject">
                                                <span class="from">Dulal Khan</span>
                                                <span class="time">Just now</span>
                                            </span>
                                            <span class="message">
                                                Hello, this is an example messages please check
                                            </span>
                                        </a>
                                    </li>

                                    <li>
                                        <a href="#">See all messages</a>
                                    </li>
                                </ul>
                            </li>
                            <!-- END INBOX DROPDOWN -->
                            <!-- BEGIN NOTIFICATION DROPDOWN -->
                            <li class="dropdown" id="header_notification_bar">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown">

                                    <i class="icon-bell-alt"></i>
                                    <span class="badge badge-warning">1</span>
                                </a>
                                <ul class="dropdown-menu extended notification">
                                    <li>
                                        <p>You have 1 new notifications</p>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="label label-important"><i class="icon-bolt"></i></span>
                                            Server #3 overloaded.
                                            <span class="small italic">34 mins</span>
                                        </a>
                                    </li>

                                    <li>
                                        <a href="#">See all notifications</a>
                                    </li>
                                </ul>
                            </li>
                            <!-- END NOTIFICATION DROPDOWN -->

                        </ul>
                    </div>
                    <!-- END  NOTIFICATION -->
                    <div class="top-nav ">
                        <ul class="nav pull-right top-menu" >
                            <!-- BEGIN SUPPORT -->
                            <li class="dropdown mtop5">

                                <a class="dropdown-toggle element" data-placement="bottom" data-toggle="tooltip" href="#" data-original-title="Chat">
                                    <i class="icon-comments-alt"></i>
                                </a>
                            </li>
                            <li class="dropdown mtop5">
                                <a class="dropdown-toggle element" data-placement="bottom" data-toggle="tooltip" href="#" data-original-title="Help">
                                    <i class="icon-headphones"></i>
                                </a>
                            </li>
                            <!-- END SUPPORT -->
                            <!-- BEGIN USER LOGIN DROPDOWN -->
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                    <img src="img/avatar1_small.jpg" alt=""/>
                                    <span class="username"><h:outputText value="#{user}"/> </span>
                                    <b class="caret"></b>
                                </a>
                                <ul class="dropdown-menu">
                                    <li><a href="#"><i class="icon-user"></i> My Profile</a></li>
                                    <li><a href="#"><i class="icon-tasks"></i> My Tasks</a></li>
                                    <li><a href="#"><i class="icon-calendar"></i> Calendar</a></li>
                                    <li class="divider"></li>
                                    <li>
                                        <div id="logout" > 
                                            <h:form class="icon-key">
                                                <h:commandLink action="#{userJSFManagedBean.logout()}"> LogOut</h:commandLink>
                                            </h:form>
                                        </div>
                                    </li>
                                </ul>
                            </li>
                            <!-- END USER LOGIN DROPDOWN -->
                        </ul>
                        <!-- END TOP NAVIGATION MENU -->
                    </div>
                </div>
            </div>
            <!-- END TOP NAVIGATION BAR -->
        </div>
        <!-- END HEADER -->
        <!-- BEGIN CONTAINER -->
        <div id="container" class="row-fluid">

            <br/><br/>
            <!-- BEGIN PAGE CONTAINER-->
            <div class="container-fluid">

                <!-- BEGIN ADVANCED TABLE widget-->
                <div class="row-fluid">
                    <div class="span12">
                        <!-- BEGIN EXAMPLE TABLE widget-->
                        <div class="widget">
                            <div class="widget-title">
                                <h4><i class="icon-reorder"></i>Managed Table</h4>
                                <span class="tools">
                                    <a href="javascript:;" class="icon-chevron-down"></a>
                                    <a href="javascript:;" class="icon-remove"></a>
                                </span>
                            </div>
                            <div class="widget-body">
                                <table class="table table-striped table-bordered" id="sample_1">
                                    <button class="btn btn-success"><i class="icon-ok icon-white"></i> Delete All</button>
                                    <thead>
                                        <tr>
                                            <th style="width:8px;"><input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes" /></th>
                                            <th>STT</th>
                                            <th>Username</th>
                                            <th>Password</th>
                                            <th class="hidden-phone" style="width: 200px;">
                                                <button class="btn btn-warning"><i class="icon-plus icon-white"></i> Create</button>
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <ui:repeat value="#{userJSFManagedBean.list}" var="in" varStatus="number">
                                            <tr class="odd gradeX">
                                                <td><input type="checkbox" class="checkboxes" value="1" /></td>
                                                <td>#{number.index}</td>
                                                <td>#{in.username}</td>
                                                <td>#{in.password}</td>
                                                <td class="hidden-phone">
                                                    <button class="btn btn-inverse"><i class="icon-refresh icon-white"></i> Update</button>
                                                    <button class="btn btn-danger"><i class="icon-remove icon-white"></i> Delete</button>
                                                </td>
                                            </tr>
                                        </ui:repeat>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <!-- END EXAMPLE TABLE widget-->
                    </div>
                </div>

                <!-- END ADVANCED TABLE widget-->

                <!-- END PAGE CONTENT-->
            </div>
            <!-- END PAGE CONTAINER-->
        </div>
        <!-- END PAGE -->

        <!-- BEGIN FOOTER -->
        <div id="footer">
            2013 copyright Admin Lab Dashboard.
            <div class="span pull-right">
                <span class="go-top"><i class="icon-arrow-up"></i></span>
            </div>
        </div>
        <!-- END FOOTER -->
        <!-- BEGIN JAVASCRIPTS -->
        <!-- Load javascripts at bottom, this will reduce page load time -->
        <script src="js/jquery-1.8.3.min.js"></script>
        <script src="assets/bootstrap/js/bootstrap.min.js"></script>   
        <script src="js/jquery.blockui.js"></script>
        <!-- ie8 fixes -->
        <!--[if lt IE 9]>
        <script src="js/excanvas.js"></script>
        <script src="js/respond.js"></script>
        <![endif]-->   
        <script type="text/javascript" src="assets/uniform/jquery.uniform.min.js"></script>
        <script type="text/javascript" src="assets/data-tables/jquery.dataTables.js"></script>
        <script type="text/javascript" src="assets/data-tables/DT_bootstrap.js"></script>
        <script src="js/scripts.js"></script>
        <script>
            jQuery(document).ready(function () {
                // initiate layout and plugins
                App.init();
            });
        </script>
    </h:body>
    <!-- END BODY -->
</html>
Cấu hình lại web.xml
web.xml
Java EJB 2016
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/login.xhtml</welcome-file>
    </welcome-file-list>
</web-app>
Cấu hình lại login.xhtml
login.xhtml
Java EJB 2016
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Login Title</title>
        <link rel="stylesheet" href="css/style_login.css"/>
    </h:head>
    <h:body>
        <div class="vid-container">
            <video id="Video1" class="bgvid back" autoplay="false" muted="muted" preload="auto" >
                <source src="http://shortcodelic1.manuelmasiacsasi.netdna-cdn.com/themes/geode/wp-content/uploads/2014/04/milky-way-river-1280hd.mp4.mp4" type="video/mp4"/>
            </video>
            <div class="inner-container">
                <video id="Video2" class="bgvid inner" autoplay="false" muted="muted" preload="auto">
                    <source src="http://shortcodelic1.manuelmasiacsasi.netdna-cdn.com/themes/geode/wp-content/uploads/2014/04/milky-way-river-1280hd.mp4.mp4" type="video/mp4"/>
                </video>
                <div class="box"><f:view>
                        <h:form> 
                            <h1>Login</h1>
                            <!--thong bao loi tu login fail-->
                            <h:messages globalOnly="true" styleClass="message_loginfail" />
                            <!--username-->
                            <div id="message"><h:message for="user" style="color: red"/></div>
                            <h:inputText id="user" value="#{userJSFManagedBean.username}" required="true" requiredMessage="Please Enter your username" pt:placeholder=" Enter your username"/>
                            <!--password-->
                            <div id="message"><h:message for="pass" style="color: red"/></div>
                            <h:inputSecret id="pass" value="#{userJSFManagedBean.password}" required="true" requiredMessage="Please Enter your username" pt:placeholder=" Enter your password"/>
                            <h:commandButton styleClass="button" action="#{userJSFManagedBean.login() }" value="Login"/> 
                            <p>Not a member? <span>Sign Up</span></p>
                        </h:form> </f:view>
                </div>
            </div>
        </div>
        <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
        <script src="js/index_login.js"></script>
    </h:body>
</html>
Xong! hoàn thiện phần Login và Show list với EJB + JPA + JSF + Mysql
Clear and build > Deploy > Run test ...


0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang