20 September 2016

JPA JSP Servlet Java Entity Database Insert Update Delete User

Create Database mysql workbench
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(45) DEFAULT NULL,
  `pass` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
1. Create class User.java  in package Entity
Source packages > new > other > Persistence > Entity Classes from Database

2. Create class UserJpaController.java in package jpaDAO
Source packages > new > other > Persistence > JPA Controller Classes from Entity Classes
User.java
Java 2016
package Entty;

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.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
    @NamedQuery(name = "User.findByUser", query = "SELECT u FROM User u WHERE u.user = :user"),
    @NamedQuery(name = "User.findByPass", query = "SELECT u FROM User u WHERE u.pass = :pass")})
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    //@Basic(optional = false)
    //@NotNull
    //@Column(name = "id")

    //ID tu tang neu su dung thi xoa 3 dong tren 
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Integer id;
    @Size(max = 45)
    @Column(name = "user")
    private String user;
    @Size(max = 45)
    @Column(name = "pass")
    private String pass;

    public User() {
    }

    public User(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.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.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "controller.User[ id=" + id + " ]";
    }

    public User(Integer id, String user, String pass) {
        this.id = id;
        this.user = user;
        this.pass = pass;
    }

}
UserJpaController.java
Java 2016
package jpaDAO;

import Entty.User;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpaDAO.exceptions.NonexistentEntityException;
import jpaDAO.exceptions.PreexistingEntityException;
import jpaDAO.exceptions.RollbackFailureException;

/**
 *
 * @author Lonely
 */
public class UserJpaController implements Serializable {

    //Chú ý ở đây các bạn cần cấu hình lại như tôi
    private EntityManager em;
    private EntityManagerFactory emf;

    public UserJpaController() throws Exception {
        emf = Persistence.createEntityManagerFactory("Shop_BonfirePU");
        
    }
    //Kết thúc cấu hình
    //Tiếp theo chỉnh sửa các method như dưới đây

    public void create(User user) throws PreexistingEntityException, RollbackFailureException, Exception {
        try {
            em = emf.createEntityManager();
            em.getTransaction().begin();
            em.persist(user);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findUser(user.getId()) != null) {
                throw new PreexistingEntityException("User " + user + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws NonexistentEntityException, RollbackFailureException, Exception {
        try {
            em = emf.createEntityManager();
            em.getTransaction().begin();
            user = em.merge(user);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        try {
            em = emf.createEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            em.remove(user);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        try {
            em = emf.createEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        try {
            em = emf.createEntityManager();
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        try {
            em = emf.createEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public User login(String username, String password) {
        em = emf.createEntityManager();
        Query q = em.createQuery("SELECT a from User a where a.user = :user AND a.pass = :pass ");
        q.setParameter("user", username);
        q.setParameter("pass", password);

        List<User> ls = q.getResultList();

        if (ls.size() == 1) {
            return ls.get(0);
        }
        return null;
    }

}

login.jsp
Java 2016
<%-- 
    Document   : login
    Created on : Sep 15, 2016, 9:41:51 AM
    Author     : Lonely
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Admin Shop</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <link rel="shortcut icon" href="stylesheet/img/devil-icon.png"> <!--Pemanggilan gambar favicon-->
        <link rel="stylesheet" type="text/css" href="mos-css/mos-style.css"> <!--pemanggilan file css-->
        <!--Validate login null--> 
        <script type="text/javascript">
            function validate()
            {
                var a = document.getElementById("a");
                var b = document.getElementById("b");
                var valid = true;
                if (a.value.length <= 0)
                {
                    alert("Username không được để trống!");
                    valid = false;
                }
                else if(b.value.length < 6){
                    alert("Password it nhat 6 ki tu");
                    valid = false;
                }
                return valid;
            };
        </script>
    </head>

    <body>
        <div id="header">
            <div class="inHeaderLogin"></div>
        </div>

        <div id="loginForm">
            <div class="headLoginForm">
                Login Administrator
            </div>
            <div class="fieldLogin">
                <form method="POST" action="<%=request.getContextPath() %>/LoginServlet" onsubmit="return validate();">
                    <label>Username</label><br>
                    <input type="text" name="user" id="a" class="login"><br>
                    <label>Password</label><br>
                    <input type="password" name="pass" id="b" class="login"><br>
                    <input type="submit" class="button" value="Login">
                </form>
            </div>
        </div>
    </body>
</html>
LoginServlet.java
Java 2016
package controller;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
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 jpaDAO.UserJpaController;

/**
 *
 * @author Lonely
 */
public class LoginServlet extends HttpServlet {
    //Login
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            
            String user = request.getParameter("user");
            String pass = request.getParameter("pass");
            
            UserJpaController u = new UserJpaController();

            if (u.login(user, pass) != null) {
                HttpSession httpSession = request.getSession(true);
                httpSession.setAttribute("user", user);
                response.sendRedirect(request.getContextPath()+"/admin/manager.jsp");
            } else {
                request.setAttribute("ERR", "Loi");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
            
        } catch (Exception ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //Logout
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
    }
}
http://localhost:8080/Shop_Bonfire/admin/admin.jsp
 http://localhost:8080/Shop_Bonfire/admin/insert-user.jsp
insert-user.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="Admin MOS Template">
        <meta name="keywords" content="Admin Page">
        <meta name="author" content="Ari Rusmanto">

        <title>Wellcome Admin</title>
        <link rel="shortcut icon" href="stylesheet/img/devil-icon.png"> <!--Pemanggilan gambar favicon-->
        <link rel="stylesheet" type="text/css" href="mos-css/mos-style.css"> <!--pemanggilan file css-->
    </head>
    <body>
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
            <jsp:include page="asider.jsp"></jsp:include>
            <div id="rightContent">
                <form action="<%=request.getContextPath()%>/UserAddServlet" method="POST">
                    <table border="1">
                        <tr class="data">
                                <th class="data">infomation</th>
                                <th class="data">Chosse input</th>
                            </tr>
                            <tr>
                                <td>Id</td>
                                <td><input type="text" name="id" value="" /><br/></td>
                            </tr>
                            <tr>
                                <td>Username</td>
                                <td><input type="text" name="user" value="" /><br/></td>
                            </tr>
                            <tr>
                                <td>Password</td>
                                <td><input type="text" name="pass" value="" /><br/></td>
                            </tr>
                           
                            <tr>
                                <td></td>
                                <td> <input type="submit" value="Insert" /></td>
                            </tr>
                    </table>
                   
                </form>
            </div>
            <div class="clear"></div>
            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
UserAddServlet.java
Java 2016
package controller;

import Entty.User;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpaDAO.UserJpaController;

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        int id = Integer.parseInt(request.getParameter("id"));
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        User u = new User();
        u.setId(id);
        u.setUser(user);
        u.setPass(pass);
        
        try {
            UserJpaController udao = new UserJpaController();
            udao.create(u);
            response.sendRedirect(request.getContextPath()+"/admin/admin.jsp");
        } catch (Exception ex) {
            Logger.getLogger(UserAddServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
http://localhost:8080/Shop_Bonfire/admin/update-user.jsp?id=1
update-user.jsp
Java 2016
<%@page import="Entty.User"%>
<%@page import="jpaDAO.UserJpaController"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="Admin MOS Template">
        <meta name="keywords" content="Admin Page">
        <meta name="author" content="Ari Rusmanto">

        <title>Welcome Admin</title>
        <link rel="shortcut icon" href="stylesheet/img/devil-icon.png"> <!--Pemanggilan gambar favicon-->
        <link rel="stylesheet" type="text/css" href="mos-css/mos-style.css"> <!--pemanggilan file css-->
    </head>
    <body>
        <div id="wrapper">
            <%
                int id1 = Integer.parseInt(request.getParameter("id"));
                UserJpaController udao = new UserJpaController();
                User user = udao.findUser(id1);
            %>

            <jsp:include page="header.jsp"></jsp:include>
            <jsp:include page="asider.jsp"></jsp:include>
                <div id="rightContent">
                    <form action="<%=request.getContextPath()%>/UserEditServlet" method="POST">
                    <table border="1">
                        <tr class="data">
                            <th class="data">infomation</th>
                            <th class="data">Chosse input</th>
                        </tr>
                        <tr>
                            <td>ID User</td>
                            <td><input type="text" name="id" value="<%=user.getId() %>" /><br/></td>
                        </tr>
                        <tr>
                            <td>Username</td>
                            <td><input type="text" name="user" value="<%=user.getUser() %>" /><br/></td>
                        </tr>
                        <tr>
                            <td>Password</td>
                            <td><input type="text" name="pass" value="<%=user.getPass() %>" /><br/></td>
                        </tr>
                        <tr>
                            <td></td>
                            <td> <input type="submit" value="Update" /></td>
                        </tr>
                  
                    </table>

                </form>
            </div>
            <div class="clear"></div>
            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
UserEditServlet.java
Java 2016
package controller;

import Entty.User;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpaDAO.UserJpaController;
import jpaDAO.exceptions.RollbackFailureException;

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");

        User u = new User();
        u.setId(id);
        u.setUser(user);
        u.setPass(pass);

        try {
            UserJpaController udao = new UserJpaController();
            udao.edit(u);
            response.sendRedirect(request.getContextPath()+"/admin/admin.jsp");
        } catch (RollbackFailureException ex) {
            Logger.getLogger(UserEditServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(UserEditServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
http://localhost:8080/Shop_Bonfire/UserDeleteServlet?id=1

admin.jsp
Java 2016
<%@page import="javax.persistence.EntityManagerFactory"%>
<%@page import="javax.transaction.UserTransaction"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="Entty.User"%>
<%@page import="java.util.List"%>
<%@page import="jpaDAO.UserJpaController"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>Wellcome Admin</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="mos-css/mos-style.css">
        <style>
            .img-danhmuc{
                width:  50px;
                height: 30px;
            }
            .add{
                display: block;
                background: #a6d050;
                line-height: 15px;
                width: 102px;
                border-radius: 5px;
                padding: 5px;
                color: white;
                font-weight: bold;
            }
            ul.pagination {
                display: inline-block;
                padding-left: 36%;
                margin: 0;
            }

            ul.pagination li {display: inline;}

            ul.pagination li a {
                color: black;
                float: left;
                padding: 8px 16px;
                text-decoration: none;
                transition: background-color .3s;
                border: 1px solid #ddd;
                font-size: 12px;
            }

            ul.pagination li a.active {
                background-color: #4CAF50;
                color: white;
                border: 1px solid #4CAF50;
            }

            ul.pagination li a:hover:not(.active) {background-color: #ddd;}
        </style>
    </head>
    <body>
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
            <jsp:include page="asider.jsp"></jsp:include>

            <%
                UserJpaController u = new UserJpaController();
                List<User> list = u.findUserEntities();
            %>

            <div id="rightContent">   
                <h3>Quản Lý Admin</h3>
                <a href="insert-user.jsp" class="add">Thêm Danh Mục</a>
                <table class="data">
                    <tr class="data">
                        <th class="data">Mã Admin</th>
                        <th class="data">Username</th>
                        <th class="data">Password</th>
                        <th colspan="2" class="data">Tùy Chọn</th>
                    </tr>
                    <% for (User item : list) {%>
                    <tr>
                        <td class="data" id="id"><%=item.getId()%></td>
                        <td class="data"><%=item.getUser()%></td>
                        <td class="data"><%=item.getPass()%></td>
                        <td class="data">
                            <a name="operation" href="update-user.jsp?id=<%=item.getId() %>"> <img src="mos-css/img/Text-Edit-icon.png"/></a>  -|-  
                            <a name="operation" href="<%=request.getContextPath()%>/UserDeleteServlet?id=<%=item.getId()%>" onclick="return confirm('Are you sure delete?')">
                                <img src="mos-css/img/delete-file-icon.png"/></a></td>
                    </tr>
                    <%}%>
                </table>
            </div>
            <div class="clear"></div>

            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
UserDeleteServlet.java
Java 2016
package controller;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpaDAO.UserJpaController;
import jpaDAO.exceptions.RollbackFailureException;

public class UserDeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int id = Integer.parseInt(request.getParameter("id"));
        
        try {
            UserJpaController u = new UserJpaController();
            u.destroy(id);
            response.sendRedirect(request.getContextPath()+"/admin/admin.jsp");
        } catch (RollbackFailureException ex) {
            Logger.getLogger(UserDeleteServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(UserDeleteServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang