29 November 2016

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

Check Login EJB với JPA server GlassFish
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 Resource vì GlassFish không tự tạo.
[1]-Tạo Pool tên connectionPool
[2]- Tạo resource tên jdbc/myDatasource
[3]-Tạo file persistence.xml
Clear and build > Deploy
Check trên Netbeans
Check trên localhost:4848

Nếu mọi nỗ lực không thành công! thì tôi xin chuyển vấn đề này qua video fix trực tiếp trên cổng 4848
Buoc 2:
JNDI Name: jdbc/myDatasource
Pool Name: connectionPool

Buoc 1:
Pool Name: connectionPool
Resource Type: javax.sql.DataSource
Driver: Mysql

URL  jdbc:mysql://localhost:3306/ejb
Password   1234567
User   root

========Xong phần tạo Resource cho GlassFish=========
-Từ bây giờ chúng ta có thể sử dụng JPA kết nối Database mysql một cách bình thường
=============================================
[1] Tạo User.java (package: entity)
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 = 25)
    @Column(name = "username")
    private String username;
    @Size(max = 25)
    @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 + " ]";
    }
    
}
[2]- Tạo Session Bean UserSessionBean.java (package: session)
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 {
    //1. Da xong! (Alt+Insert > Use Entity Manager..)

    @PersistenceContext(unitName = "EnterpriseApplication3-ejbPU")
    private EntityManager em;

    //Create checkLogin (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;
        }
    }

    public void persist(Object object) {
        em.persist(object);
    }

} 
UserSessionBeanLocal.java
Java EJB 2016
package session;

import javax.ejb.Local;

/**
 *
 * @author Lonely
 */
@Local
public interface UserSessionBeanLocal {

    boolean checkLogin(String username, String password);
    
}
[3]- Tạo LoginServlet.java
LoginServlet.java
Java EJB 2016
package controller;

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.UserSessionBeanLocal;

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

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            if (userSessionBean.checkLogin(username, password)) {
                HttpSession session = request.getSession();
                request.setAttribute("username", username);
                session.setAttribute("user", username);
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }else{
                request.getRequestDispatcher("invalid.jsp").forward(request, response);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}
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">
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>controller.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    //Cấu hình lại web.xml đặt địa chỉ view đầu tiên là login.jsp
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>
[4]- Tạo page
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" value="" /><br/>
           Password <input type="password" name="password" value="" /><br/>
            <input type="submit" value="Login" />
        </form>
    </body>
</html>
index.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>Welcome home!</h1>
        <font color="red" size="6">
        Att: ${requestScope.username}<br/>
        Ses: ${sessionScope.user}
        </font>
    </body>
</html>
invalid.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>
        <font color="red"><h1>Invalid !</h1></font>
    </body>
</html>
Click vào project tam giác > Clear and build > Deploy > Run


Login success!
Login fail!
Download (Zip import NetBeans)

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang