IMG-LOGO
Trang Chủ Chủ Đề [Share Code - Video] Dự án quản lý sinh viên + CSDL - Database SQL Server - MySQL - Lập trình JSP/Servlet
× 1) [Share Code] Tìm hiểu JSP/Servlet - Tạo dự án đầu tiên + Truyền dữ liệu từ Servlet sang JSP 2) [Share Code] Tìm hiểu GET/POST - Session - Cookie trong JSP/Servlet - Lập trình JSP/Servlet 3) [Share Code] Chữa bài tập - Đăng Ký & Đăng Nhập - Ứng dụng session servlet - Lập trình JSP/Servlet 4) [Share Code] Hướng dẫn tìm hiểu request, response, session, application trong JSP - jsp include, forward, param - JavaBean trong JSP/Servlet 5) [Shade Code] Tìm hiểu EL trong JSP & jstf trong JSP - Lập trình JSP Servlet 6) [Share Code] Bài tập quản lý sản phẩm sử dụng Session, JSTL, JavaBean trong lập trình JSP/Servlet 7) [Share Code] Hướng kết nối CSDL MySQL trong JSP/Servlet - Lập trình JSP/Servlet 8. [Share Code - Video] Dự án quản lý sinh viên + CSDL - Database SQL Server - MySQL - Lập trình JSP/Servlet 9) [Share Code] Source Code - Quản lý tin tức - JSP/Servlet 10) [Share Code] Tìm hiểu JSP Servlet lớp J2010G - Lập trình JSP Servlet 11) [Share Code] Tìm hiểu JSTL + Cookie + Session - Lập trình JSP/Servlet 12) [Share Code] Chia sẻ code tìm hiểu JDBC - Kết nối CSDL - Lập trình JSP/Servlet

[Share Code - Video] Dự án quản lý sinh viên + CSDL - Database SQL Server - MySQL - Lập trình JSP/Servlet

by TRẦN VĂN ĐIỆP - 23:53 21/11/2020 1,607 Lượt Xem

Dự án quản lý sinh viên + CSDL - Database SQL Server - MySQL - Lập trình JSP/Servlet



B1. Tao Project
B2. Thiet ke database -> StudentManagement
create table Student (
	id int primary key auto_increment,
	fullname varchar(50),
	age int,
	address varchar(200)
)
B3. Generate Entity trong Project <=> database
- Tai thu vien jdbc mysql driver => add project
- Tao connection project <=> database
B4. Phan tich project
- Add Student
	- Servlet: AddServlet
	- Route: /add
	- JSP: addStudent.jsp
- List Student
	- Servlet: ListServlet
	- Route: /list
	- JSP: listStudent.jsp





#addStudent.jsp


<%-- 
    Document   : addStudent
    Created on : Aug 24, 2020, 7:39:48 PM
    Author     : Diep
--%>

<%@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 Student</h2>
			</div>
			<div class="panel-body">
                            <form method="post">
				<div class="form-group">
				  <label for="usr">Name:</label>
                                  <input type="text" name="id" value="${std.id}" style="display: none;"/>
                                  <input required="true" type="text" class="form-control" value="${std.fullname}" id="usr" name="name"/>
				</div>
				<div class="form-group">
				  <label for="email">Age:</label>
                                  <input required="true" type="number" class="form-control" value="${std.age}" id="age" name="age"/>
				</div>
				<div class="form-group">
				  <label for="address">Address:</label>
                                  <input type="text" class="form-control" id="address" value="${std.address}" name="address"/>
				</div>
				<button class="btn btn-success">Register</button>
                            </form>
			</div>
		</div>
	</div>
</body>
</html>


#listStudent.jsp


<%-- 
    Document   : addStudent
    Created on : Aug 24, 2020, 7:39:48 PM
    Author     : Diep
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>List 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">List Student</h2>
			</div>
			<div class="panel-body">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>STT</th>
                                        <th>Ho & Ten</th>
                                        <th>Tuoi</th>
                                        <th>Dia Chi</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach var="std" items="${studentList}" varStatus="loop">
                                        <tr>
                                            <td>${loop.index + 1}</td>
                                            <td>${std.fullname}</td>
                                            <td>${std.age}</td>
                                            <td>${std.address}</td>
                                            <td>
                                                <a href="add?id=${std.id}">
                                                    <button class="btn btn-warning">Edit</button>
                                                </a>
                                            </td>
                                            <td>
                                                <form method="post">
                                                    <input type="text"  value="${std.id}" name="id" style="display: none;"/>
                                                    <button class="btn btn-danger">Delete</button>
                                                </form>
                                            </td>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>
			</div>
		</div>
	</div>
</body>
</html>


#AddServlet.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 servlet;

import entities.Student;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Diep
 */
public class AddServlet extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Student std = new Student(0);
        
        if(request.getParameter("id") != null) {
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("StudentProjectPU");
            EntityManager em = factory.createEntityManager();
            int id = Integer.parseInt(request.getParameter("id"));
            std = em.find(Student.class, id);
        }
        
        request.setAttribute("std", std);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/student/addStudent.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        int id = Integer.parseInt(request.getParameter("id"));
        int age = Integer.parseInt(request.getParameter("age"));
        String address = request.getParameter("address");
        
        //Save into database
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("StudentProjectPU");
        EntityManager em = factory.createEntityManager();
        
        if(id == 0) {
            Student std = new Student();
            std.setFullname(name);
            std.setAge(age);
            std.setAddress(address);

            em.getTransaction().begin();
            em.persist(std);
            em.getTransaction().commit();
        } else {
            Student editStd = em.find(Student.class, id);

            em.getTransaction().begin();
            editStd.setFullname(name);
            editStd.setAge(age);
            editStd.setAddress(address);
            em.getTransaction().commit();
        }
        
        response.sendRedirect("add");
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


#ListServlet.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 servlet;

import entities.Student;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Diep
 */
public class ListServlet extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("StudentProjectPU");
        EntityManager em = factory.createEntityManager();
        
        Query q = em.createNamedQuery("Student.findAll", Student.class);
        List<Student> studentList = q.getResultList();
        
        request.setAttribute("studentList", studentList);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/student/listStudent.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("StudentProjectPU");
        EntityManager em = factory.createEntityManager();
        
        Student std = em.find(Student.class, id);
        
        em.getTransaction().begin();
        em.remove(std);
        em.getTransaction().commit();
        
        response.sendRedirect("list");
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


#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 entities;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Diep
 */
@Entity
@Table(name = "student")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s")
    , @NamedQuery(name = "Student.findById", query = "SELECT s FROM Student s WHERE s.id = :id")
    , @NamedQuery(name = "Student.findByFullname", query = "SELECT s FROM Student s WHERE s.fullname = :fullname")
    , @NamedQuery(name = "Student.findByAge", query = "SELECT s FROM Student s WHERE s.age = :age")
    , @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
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Size(max = 50)
    @Column(name = "fullname")
    private String fullname;
    @Column(name = "age")
    private Integer age;
    @Size(max = 200)
    @Column(name = "address")
    private String address;

    public Student() {
    }

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

    public Integer getId() {
        return id;
    }

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

    public String getFullname() {
        return fullname;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

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

    @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 Student)) {
            return false;
        }
        Student other = (Student) 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 "entities.Student[ id=" + id + " ]";
    }
    
}


Theo dõi cập nhật nội dung học trên Youtube


Bình luận



Chia sẻ từ lớp học

Danh Sách Bài Học

Quick Quizzz!!!

User ImageUser ImageUser Image
User ImageUser ImageUser Image
User ImageUser ImageUser Image
User ImageUser ImageUser Image
User ImageUser ImageUser Image
User Image
User ImageUser ImageUser Image
>> Hiển Thị Quizzz
Đã sao chép!!!