By GokiSoft.com| 19:44 26/10/2020|
Java Web + EJB (EAD)

[Share Code] Hướng dẫn chữa bài tập quản lý sinh viên - Lập trình EJB EAD

EJB


#persistence.xml


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="QuanLySinhVien-ejbPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>entity.Student</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/quanlysinhvien?serverTimezone=UTC"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value=""/>
    </properties>
  </persistence-unit>
</persistence>


#StudentSessionBean.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import entity.Student;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author student
 */
@Stateless
public class StudentSessionBean implements StudentSessionBeanLocal {
    @Override
    public List<Student> findAll() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("QuanLySinhVien-ejbPU");
        EntityManager em = factory.createEntityManager();
        
        Query q = em.createNamedQuery("Student.findAll", Student.class);
        
        return q.getResultList();
    }

    @Override
    public Student find(String rollno) {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("QuanLySinhVien-ejbPU");
        EntityManager em = factory.createEntityManager();
        
        Student std = em.find(Student.class, rollno);
        
        return std;
    }

    @Override
    public void save(Student std) {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("QuanLySinhVien-ejbPU");
        EntityManager em = factory.createEntityManager();
        
        Student stdFind = em.find(Student.class, std.getRollno());
        System.out.println(std);
        if(stdFind != null) {
            em.getTransaction().begin();
            stdFind.setAddress(std.getAddress());
            stdFind.setFullname(std.getFullname());
            em.getTransaction().commit();
        } else {
            em.getTransaction().begin();
            em.persist(std);
            em.getTransaction().commit();
        }
    }

    @Override
    public void delete(String rollno) {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("QuanLySinhVien-ejbPU");
        EntityManager em = factory.createEntityManager();
        
        Student std = em.find(Student.class, rollno);
        
        if(std != null) {
            em.getTransaction().begin();
            em.remove(std);
            em.getTransaction().commit();
        }
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}


#StudentSessionBeanLocal.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

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

/**
 *
 * @author student
 */
@Local
public interface StudentSessionBeanLocal {
    List<Student> findAll();
    
    Student find(String rollno);
    
    void save(Student std);
    
    void delete(String rollno);
}


#Student.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
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 student
 */
@Entity
@Table(name = "student")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s")
    , @NamedQuery(name = "Student.findByRollno", query = "SELECT s FROM Student s WHERE s.rollno = :rollno")
    , @NamedQuery(name = "Student.findByFullname", query = "SELECT s FROM Student s WHERE s.fullname = :fullname")
    , @NamedQuery(name = "Student.findByAddress", query = "SELECT s FROM Student s WHERE s.address = :address")})
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "rollno")
    private String rollno;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "fullname")
    private String fullname;
    @Size(max = 200)
    @Column(name = "address")
    private String address;

    public Student() {
    }

    public Student(String rollno) {
        this.rollno = rollno;
    }

    public Student(String rollno, String fullname) {
        this.rollno = rollno;
        this.fullname = fullname;
    }

    public String getRollno() {
        return rollno;
    }

    public void setRollno(String rollno) {
        this.rollno = rollno;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

    @Override
    public String toString() {
        return "Student{" + "rollno=" + rollno + ", fullname=" + fullname + ", address=" + address + '}';
    }
    
}

Web Client


#home.jsp


<%-- 
    Document   : home
    Created on : Oct 26, 2020, 7:05:48 PM
    Author     : student
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Student List</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/>

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Student List</h2>
			</div>
			<div class="panel-body">
                            <a href="view.html"><button class="btn btn-success">Add new student</button></a>
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>STT</th>
                                        <th>Roll No</th>
                                        <th>FullName</th>
                                        <th>Address</th>
                                        <th width="50px"></th>
                                        <th width="50px"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach items="${studentList}" var="item" varStatus="loop">
                                        <tr>
                                            <td>${loop.index + 1}</td>
                                            <td>${item.rollno}</td>
                                            <td>${item.fullname}</td>
                                            <td>${item.address}</td>
                                            <td>
                                                <a href="view.html?rollno=${item.rollno}"><button class="btn btn-warning">Edit</button></a>
                                            </td>
                                            <td>
                                                <button class="btn btn-danger" onclick="deleteStudent('${item.rollno}')">Delete</button>
                                            </td>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>
			</div>
		</div>
	</div>
    
    <script>
        function deleteStudent(rollno) {
            $.post('delete.html', {
                rollno: rollno
            }, function(data) {
                location.reload();
            })
        }
    </script>
</body>
</html>


#index.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Spring Web MVC project</title>
    </head>

    <body>
        <p>Hello! This is the default welcome page for a Spring Web MVC project.</p>
        <p><i>To display a different welcome page for this project, modify</i>
            <tt>index.jsp</tt> <i>, or create your own welcome page then change
                the redirection in</i> <tt>redirect.jsp</tt> <i>to point to the new
                welcome page and also update the welcome-file setting in</i>
            <tt>web.xml</tt>.</p>
    </body>
</html>


#view.jsp


<%-- 
    Document   : view
    Created on : Oct 26, 2020, 7:14:49 PM
    Author     : student
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Add Student</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/>

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Add New Student</h2>
			</div>
			<div class="panel-body">
                            <form method="post" action="save.html">
				<div class="form-group">
				  <label for="usr">Name:</label>
                                  <input required="true" type="text" class="form-control" id="usr" name="fullname" value="${student.fullname}">
				</div>
				<div class="form-group">
				  <label for="email">RollNo:</label>
                                  <input required="true" type="text" class="form-control" id="rollno" name="rollno" value="${student.rollno}">
				</div>
				<div class="form-group">
				  <label for="address">Address:</label>
                                  <input type="text" class="form-control" id="address" name="address" value="${student.address}">
				</div>
				<button class="btn btn-success">Register</button>
                            </form>
			</div>
		</div>
	</div>
</body>
</html>


#dispatcher-servlet.xml


<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <context:component-scan base-package="controller"></context:component-scan>
    <mvc:annotation-driven/>
    
    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.html">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/view/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

</beans>


#StudentController.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entity.Student;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import session.StudentSessionBeanLocal;

/**
 *
 * @author student
 */
@Controller
@RequestMapping(value = "/student")
public class StudentController {
    StudentSessionBeanLocal studentSessionBean = lookupStudentSessionBeanLocal();
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String showHome(ModelMap modelMap) {
        List<Student> studentList = studentSessionBean.findAll();
        modelMap.put("studentList", studentList);
        return "home";
    }
    
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(@RequestParam HashMap<String, String> form, ModelMap modelMap) {
        Student std = new Student();
        if(form.containsKey("rollno")) {
            String rollno = form.get("rollno");
            std = studentSessionBean.find(rollno);
        }
        modelMap.put("student", std);
        return "view";
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@RequestParam HashMap<String, String> form) {
        String rollno = form.get("rollno");
        String fullname = form.get("fullname");
        String address = form.get("address");
        
        Student std = new Student();
        std.setAddress(address);
        std.setFullname(fullname);
        std.setRollno(rollno);
        
        studentSessionBean.save(std);
        
        return "redirect:list.html";
    }
    
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public void delete(@RequestParam HashMap<String, String> form) {
        if(form.containsKey("rollno")) {
            String rollno = form.get("rollno");
            studentSessionBean.delete(rollno);
        }
//        return "redirect:list.html";
    }

    private StudentSessionBeanLocal lookupStudentSessionBeanLocal() {
        try {
            Context c = new InitialContext();
            return (StudentSessionBeanLocal) c.lookup("java:global/QuanLySinhVien/QuanLySinhVien-ejb/StudentSessionBean!session.StudentSessionBeanLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)