By GokiSoft.com| 07:14 03/10/2021|
JSP Servlet

Hướng dẫn code API Backend + Frontend - Tạo 2 dự án đọc lập


Phân tích



Học cách viết API <=> JSP/Servlet

Chương trình quản lý sinh viên: Hiển thị danh sách, thêm, sửa, xoá
Trường thông tin cần quản lý với 1 sinh viên: rollno, fullname, email, address, birthday

Backend: (Server : JSP/Servlet)
	- Chức năng

Frontend: (HTML/CSS/JS + Bootstrap)
	- Hiển thị => Tạo giao diện của web.

=================================================
Các bước phát triển
=================================================
B1. Định Nghĩa API

Base URL: http://localhost:8080/StudentManagement

API_1: Lấy danh sách sinh viên
	Tên API : /api/student/list
	Method: GET
	Request: NONE
	Response: [
		{
			'rollno': 'R001',
			'fullname': 'Tran Van A',
			'email': 'a@gmail.com',
			'address': 'Nam Dinh',
			'birthday': '1999-02-06'
		},{
			'rollno': 'R002',
			'fullname': 'Tran Van B',
			'email': 'b@gmail.com',
			'address': 'Nam Dinh',
			'birthday': '1999-06-06'
		}
	]

API_2: Them sinh vien
	Ten API: /api/student/add
	Method: POST
	Request: 'data': {
		'rollno': 'R003',
		'fullname': 'Tran Van C',
		'email': 'c@gmail.com',
		'address': 'Nam Dinh',
		'birthday': '1999-08-06'
	}
	Response: {
		'status': 'success', //error, succes
		'message': 'Them sinh vien thanh cong'
	}

API_3: Sua thong tin sinh vien
	Ten API: /api/student/update
	Method: POST
	Request: 'data': {
		'rollno': 'R003',
		'fullname': 'Tran Van C',
		'email': 'c@gmail.com',
		'address': 'Nam Dinh',
		'birthday': '1999-08-06'
	}
	Response: {
		'status': 'success', //error, succes
		'message': 'Them sinh vien thanh cong'
	}
API_4: Xoa sinh vien
	Ten API: /api/student/delete
	Method: POST
	Request: 'data': {
		'rollno': 'R003'
	}
	Response: {
		'status': 'success', //error, succes
		'message': 'Them sinh vien thanh cong'
	}

B2. Phat trien Backend
Thiet ke database : StudentManagement
create table student (
	rollno varchar(20) primary key,
	fullname varchar(50),
	email varchar(150),
	address varchar(200),
	birthday date
)

Ket noi CSDL <=> Project
ORM (Entity) => Project




Frontend:



const BASE_URL = 'http://localhost:8080/StudentMgr'

// Sinh Vien
const API_STUDENT_LIST = '/api/student/list'
const API_STUDENT_ADD = '/api/student/add'
const API_STUDENT_UPDATE = '/api/student/update'
const API_STUDENT_DELETE = '/api/student/delete'



<!DOCTYPE html>
<html>
<head>
	<title>Danh Sách Sinh Viên</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>

	<script type="text/javascript" src="api_config.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Danh Sách Sinh Viên</h2>
			</div>
			<div class="panel-body">
				<table class="table table-bordered">
					<thead>
						<tr>
							<th>RollNo</th>
							<th>FullName</th>
							<th>Email</th>
							<th>Birthday</th>
							<th>Address</th>
						</tr>
					</thead>
					<tbody id="studentList">
					</tbody>
				</table>
			</div>
		</div>
	</div>

	<script type="text/javascript">
		$(function() {
			$.get(BASE_URL + API_STUDENT_LIST, function(data) {
				var studentList = data//JSON.parse(data)
				for (var i = studentList.length - 1; i >= 0; i--) {
					$('#studentList').append(`<tr>
							<td>${studentList[i].rollno}</td>
							<td>${studentList[i].fullname}</td>
							<td>${studentList[i].email}</td>
							<td>${studentList[i].birthday}</td>
							<td>${studentList[i].address}</td>
						</tr>`)
				}
			})
		})
	</script>
</body>
</html>



Backend



<?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="StudentMgrPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>entities.Student</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/student_mgr?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>



/*
 * 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 com.google.gson.Gson;
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.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, String json)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:82");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println(json);
        }
    }

    // <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("StudentMgrPU");
        EntityManager em = factory.createEntityManager();
        
        Query q = em.createNamedQuery("Student.findAll", Student.class);
        
        List<Student> list = q.getResultList();
        
        //convert string => object hoac nguoc lai => lib gson
        Gson gson = new Gson();
        String json = gson.toJson(list);
        
        processRequest(request, response, json);
    }

    /**
     * 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 {
    }

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

}





Tags:



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

5

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

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó