29 November 2016

EJB3: Show Data List (EJB + Persistence + JSP + Mysql) P2

Show dữ liệu bằng EJB & JPA lên JSP/Servlet
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;
        }
    }

    public void persist(Object object) {
        em.persist(object);
    }
    // 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();
    }

}
UserSessionBeanLocal.java
Java EJB 2016
package session;

import entity.User;
import java.util.List;
import javax.ejb.Local;

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

    boolean checkLogin(String username, String password);

    List<User> findAll();
    
}
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 {

    @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.setAttribute("items", userSessionBean.findAll());
                
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }else{
                request.getRequestDispatcher("invalid.jsp").forward(request, response);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}
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>
        <h1>Welcome home!</h1>
        <font color="red" size="6">
        Att: ${requestScope.username}<br/>
        Ses: ${sessionScope.user}
        </font>
        <table border="1">
            <tr>
                <th>No.</th>
                <th>Username</th>
                <th>Password</th>
            </tr>
            <c:forEach var="it" items="${items}" varStatus="number">
                <tr>
                    //Note: Nếu làm project để dùng thi ta cần thêm <c:out value=""/> để tránh lỗi XSS
                    <td>${number.count}</td>
                    <td>${it.username}</td>
                    <td>${it.password}</td>
                </tr>
            </c:forEach>
        </table>

    </body>
</html>
 Clear and build > Deploy > Run
Login user: Antonio pass: 123456
Login success show data list

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang