30 November 2016

EJB3: Search & Logout (EJB + Persistence + JSP + Mysql) P3

Search với Like
Cấu hình thêm trong entity User.java
Ở đây chúng ta gọi query bằng tên User.findByLikeUsername
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"),
    @NamedQuery(name = "User.findByLikeUsername", query = "SELECT u FROM User u WHERE u.username Like :username")})
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 + " ]";
    }
    
}
UserSessionBean.java
Java EJB 2016
package session;

import entity.User;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 *
 * @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 > Call Enterpride Bean..)
    @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() {
        Query query = em.createNamedQuery("User.findAll");
        return query.getResultList();
    }

    //Alt + Insert > Add Business Method..
    @Override
    public List<User> search(String txtSearch) {
        Query query = em.createNamedQuery("User.findByLikeUsername");
        query.setParameter("username", "%"+txtSearch+"%");
        return query.getResultList();
    }

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

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

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

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (userSessionBean.checkLogin(username, password)) {
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            request.setAttribute("items", userSessionBean.findAll());
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("invalid.jsp").forward(request, response);
        }
    }

}
Note: Tạo mới servlet SCUDServlet cần đi đến step 3 để add tên servlet vào web.xml như vậy chúng ta sẽ không cần cấu hình bằng tay trong web.xml
SCUDServlet.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.UserSessionBeanLocal; /** * * @author Lonely */ public class SCUDServlet extends HttpServlet { //Alt+Insert > Call Enterpride Bean.. @EJB private UserSessionBeanLocal userSessionBean; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Insert + Update + Delete } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String txtSearch = request.getParameter("txtSearch"); if (userSessionBean.search(txtSearch) != null) { //Search request.setAttribute("items", userSessionBean.search(txtSearch)); request.getRequestDispatcher("index.jsp").forward(request, response); } else { //Error request.getRequestDispatcher("error.jsp").forward(request, response); } } }
index.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> <font color="red"> Welcome: ${sessionScope.username} <a href="LoginServlet">LogOut</a> </font> <table border="1"> <tr> <th>No.</th> <th>Username</th> <th>Password</th> </tr> <c:forEach var="it" items="${items}" varStatus="num"> <tr> <td>${num.count}</td> <td>${it.username}</td> <td>${it.password}</td> </tr> </c:forEach> <form name="action" action="SearchServlet" > <tr> <td colspan="3"> Username:<input type="text" name="txtSearch" /> <input type="submit" value="Search" /> </td> </tr> </form> </table> </body> </html>
Click vào hình tam giác project Clear and build > Deploy > Run
Login Antonio 123456
Login Success!
Search A
Search E 

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang