30 November 2016

EJB3: Insert Update Delete (EJB + Persistence + JSP + Mysql) P4

Thêm Sửa Xóa EJB với Entity JPA GlassFish

UserSessionBean.java
Java EJB 2016
package session;

import entity.User;
import java.util.List;
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 = "EnterpriseApplication3-ejbPU")
    private EntityManager em;

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

    //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() {
        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();
    }

    //Alt + Insert > Add Business Method..
    @Override
    public boolean insert(String username, String password) {
        User u = em.find(User.class, username);
        if (u == null) {
            u = new User();
            u.setUsername(username);
            u.setPassword(password);
            em.persist(u);
            return true;
        }
        return false;
    }

    //Alt + Insert > Add Business Method..
    @Override
    public boolean update(String username, String password) {
        User u = em.find(User.class, username);
        if (u != null) {
            u = new User();
            u.setUsername(username);
            u.setPassword(password);
            em.merge(u);
            return true;
        }
        return false;
    }

    //Alt + Insert > Add Business Method..
    @Override
    public boolean delete(String username) {
        User u = em.find(User.class, username);
        if (u != null) {
            em.remove(u);
            return true;
        }
        return false;
    }

}
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 {
        String action = request.getParameter("action");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if ("Insert".equalsIgnoreCase(action)) {

            if (userSessionBean.insert(username, password)) {
                request.setAttribute("items", userSessionBean.findAll());
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } else {
                request.getRequestDispatcher("error.jsp").forward(request, response);
            }
        } else if ("Update".equalsIgnoreCase(action)) {
            if (userSessionBean.update(username, password)) {
                request.setAttribute("items", userSessionBean.findAll());
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } else {
                request.getRequestDispatcher("error.jsp").forward(request, response);
            }
        } else if ("Delete".equalsIgnoreCase(action)) {
            if (userSessionBean.delete(username)) {
                request.setAttribute("items", userSessionBean.findAll());
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } else {
                request.getRequestDispatcher("error.jsp").forward(request, response);
            }
        } else {
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String txtSearch = request.getParameter("txtSearch");
        if ("".equalsIgnoreCase(txtSearch) || 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);
        }
    }

}
insert.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>
        <form action="SCUDServlet" method="POST">
            Username: <input type="text" name="username" /><br/>
            Password: <input type="text" name="password" /><br/>
            <input type="submit" value="Insert" name="action" />
        </form>
    </body>
</html>
index.jsp
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>
                <th colspan="2"><a href="insert.jsp">Insert</a></th>
            </tr>
            <c:forEach var="it" items="${items}" varStatus="num">
                <form name="action" action="SCUDServlet" method="POST">
                    <tr>
                        <td>${num.count}</td>
                        <td><input type="text" name="username" value="${it.username}" /></td>
                        <td><input type="text" name="password" value="${it.password}" /></td>
                        <td><input type="submit" value="Update" name="action"/></td>
                        <td><input type="submit" value="Delete" name="action"/></td>
                    </tr>
                </form>
            </c:forEach>
            <form name="action" action="SCUDServlet">
                <tr>
                    <td colspan="5">
                        Username:<input type="text" name="txtSearch" />
                        <input type="submit" value="Search" />
                    </td>
                </tr>
            </form>
        </table>
    </body>
</html>
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>servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SCUDServlet</servlet-name>
        <servlet-class>servlet.SCUDServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SCUDServlet</servlet-name>
        <url-pattern>/SCUDServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>
Clear and build > Deploy > Run test
Login Antonio 123456
Login success!
Insert Manstein 123456
Update Manstein 123456Erich
Delete Manstein 
Download.zip (Import NetBeans)

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang