By GokiSoft.com| 10:14 03/08/2022|
Spring MVC

[Source Code] Kết nối CSDL trong Java Web - Spring MVC - C2010G



Tour:
	- TourController
	- Route:
		tour/list
			- Hien thi danh sach cac tour du lich
			- URL: tour/list.html
			- TourController
				- index
		tour/add
			- Hien thi form cho phep nhap thong tin
			- URL: tour/add.html
			- TourController
				- add
		tour/confirmAdd
			- Lay thong tin du lieu gui tu client len server -> Luu lai du lieu (DB)
			- URL: tour/confirm-add.html
			- TourController
				- confirmAdd

	B2) Tao Controller
		- Tao function tuong ung
		- Tao Model chuc nang

Them/sua/xoa/hien thi danh sach Tour -> Ket noi CSDL

B1) JDBC -> ...
B2) Thiết kế CSDL
- C2010G
create database C2010G
- Tao tables: tours
create table tours (
	id int primary key auto_increment,
	title varchar(250),
	thumbnail varchar(500),
	address varchar(250),
	tour_date datetime,
	price float,
	content longtext
)
-> DONE
B3) Ket noi CSDL -> du an (Persistence) -> ORM
- config ket noi CSDL
- Gen ORM -> Su dung
- Check config persistence
- Xu ly logic:

Khai niem:
Java Bean: JSTL -> giao tiep jsp <-> servlet
	- Class Object
		- Ke thua: Serializable
		- Thuoc tinh: default
		- Ham tao ko doi so
		- Getter/Setter

Chu y:
	JSTL: ${tour.address} -> tour.getAddress()




#TourController.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 com.gokisoft.controller;

import com.gokisoft.entities.TourEx;
import com.gokisoft.entities.Tours;
import com.gokisoft.models.Tour;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
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;

/**
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/tour")
public class TourController {
    EntityManagerFactory factory;
    EntityManager manager;
    
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap modelMap) {
        //Fake du lieu -> Hien thi ra views
//        List<Tour> tourList = new ArrayList<>();
//        
//        for (int i = 0; i < 10; i++) {
//            tourList.add(new Tour("Tour 1", "Noi dung 1", 
//                "https://gokisoft.com/uploads/stores/49/2021/10/bai-tap-spring-boot.jpg", 
//                "Ha Noi", "2022-02-12", 
//                100000));
//        }
        factory = Persistence.createEntityManagerFactory("SpringMVCPU");
        manager = factory.createEntityManager();
        
        Query query = manager.createNamedQuery("Tours.findAll", Tours.class);
        List<Tours> tourList = query.getResultList();
        
        List<TourEx> list = new ArrayList<>();
        for (Tours tour : tourList) {
            list.add(new TourEx(tour));
        }
        
        modelMap.addAttribute("tourList", list);
        
//        return "tour/index";
        return "tour/index-new";
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap modelMap) {
        return "tour/add";
    }
    
    @RequestMapping(value = "/confirm-add", method = RequestMethod.POST)
    public String confirmAdd(@RequestParam HashMap<String, String> formData, ModelMap modelMap) {
        String title = formData.get("title");
        String thumbnail = formData.get("thumbnail");
        String address = formData.get("address");
        String dateTime = formData.get("dateTime");
        float price = Float.parseFloat(formData.get("price"));
        String content = formData.get("content");
        
//        Tour tour = new Tour(title, content, thumbnail, address, dateTime, price);
        
        Tours tour = new Tours();
        tour.setTitle(title);
        tour.setThumbnail(thumbnail);
        tour.setAddress(address);
        tour.setPrice(price);
        tour.setContent(content);
        
        try {  
            Date mydate=new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateTime);
            tour.setTourDate(mydate);
        } catch (ParseException ex) {
            Logger.getLogger(TourController.class.getName()).log(Level.SEVERE, null, ex);
            tour.setTourDate(new Date());
        }
        
        //Khai bao - khoi tao ket
        factory = Persistence.createEntityManagerFactory("SpringMVCPU");
        manager = factory.createEntityManager();
        
        manager.getTransaction().begin();
        manager.persist(tour);
        manager.getTransaction().commit();
        
        return "redirect:index.html";
    }
}


#TourEx.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 com.gokisoft.entities;

import java.text.Format;
import java.text.SimpleDateFormat;

/**
 *
 * @author Administrator
 */
public class TourEx{
    Tours tour;

    public TourEx(Tours tour) {
        this.tour = tour;
    }
    
    public String getTourDateEx() {
        Format formatter = new SimpleDateFormat("HH:mm dd/MM/yyyy");
        String s = formatter.format(tour.getTourDate());
        
        return s;
    }

    public Tours getTour() {
        return tour;
    }

    public void setTour(Tours tour) {
        this.tour = tour;
    }
}


#Tours.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 com.gokisoft.entities;

import java.io.Serializable;
import java.util.Date;
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.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Administrator
 */
@Entity
@Table(name = "tours")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Tours.findAll", query = "SELECT t FROM Tours t")
    , @NamedQuery(name = "Tours.findById", query = "SELECT t FROM Tours t WHERE t.id = :id")
    , @NamedQuery(name = "Tours.findByTitle", query = "SELECT t FROM Tours t WHERE t.title = :title")
    , @NamedQuery(name = "Tours.findByThumbnail", query = "SELECT t FROM Tours t WHERE t.thumbnail = :thumbnail")
    , @NamedQuery(name = "Tours.findByAddress", query = "SELECT t FROM Tours t WHERE t.address = :address")
    , @NamedQuery(name = "Tours.findByTourDate", query = "SELECT t FROM Tours t WHERE t.tourDate = :tourDate")
    , @NamedQuery(name = "Tours.findByPrice", query = "SELECT t FROM Tours t WHERE t.price = :price")})
public class Tours implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "title")
    private String title;
    @Column(name = "thumbnail")
    private String thumbnail;
    @Column(name = "address")
    private String address;
    @Column(name = "tour_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date tourDate;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Column(name = "price")
    private Float price;
    @Lob
    @Column(name = "content")
    private String content;

    public Tours() {
    }

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

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public String getAddress() {
        return address;
    }

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

    public Date getTourDate() {
        return tourDate;
    }

    public void setTourDate(Date tourDate) {
        this.tourDate = tourDate;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

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


#Tour.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 com.gokisoft.models;

import java.io.Serializable;

/**
 *
 * @author Administrator
 */
public class Tour implements Serializable{
    String title, content, thumbnail, address, dateTime;
    int price;

    public Tour() {
    }

    public Tour(String title, String content, String thumbnail, String address, String dateTime, int price) {
        this.title = title;
        this.content = content;
        this.thumbnail = thumbnail;
        this.address = address;
        this.dateTime = dateTime;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public String getAddress() {
        return address;
    }

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

    public String getDateTime() {
        return dateTime;
    }

    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}


#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="SpringMVCPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>com.gokisoft.entities.Tours</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/c2010g"/>
      <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>


#add.jsp


<%-- 
    Document   : add
    Created on : Aug 3, 2022, 8:42:58 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>View - Form Add New Tour</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">Add new tour</h1>
            <div class="row">
                <div class="col-md-12">
                    <form method="post" action="confirm-add.html">
                        <div class="form-group">
                            <label>Title: </label>
                            <input required="true" type="text" name="title" class="form-control" placeholder="Enter title"/>
                        </div>
                        <div class="form-group">
                            <label>Thumbnail: </label>
                            <input required="true" type="text" name="thumbnail" class="form-control" placeholder="Enter thumbnail"/>
                        </div>
                        <div class="form-group">
                            <label>Address </label>
                            <input required="true" type="text" name="address" class="form-control" placeholder="Enter address"/>
                        </div>
                        <div class="form-group">
                            <label>Tour Date: </label>
                            <input required="true" type="datetime-local" name="dateTime" class="form-control" placeholder="Enter tour date"/>
                        </div>
                        <div class="form-group">
                            <label>Price </label>
                            <input required="true" type="number" name="price" class="form-control" placeholder="Enter price"/>
                        </div>
                        <div class="form-group">
                            <label>Description: </label>
                            <textarea class="form-control" name="content" rows="5"></textarea>
                        </div>
                        <button class="btn btn-success">Add tour</button>
                        <p style="margin-top: 20px">
                            <a href="index.html">Back to tour list</a>
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>


#index.jsp


<%-- 
    Document   : index
    Created on : Aug 3, 2022, 8:42:49 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Tour List</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">Tour List</h1>
            <a href="add.html"><button class="btn btn-success" style="margin-bottom: 20px">Add new tour</button></a>
            <table class="table table-hovered">
                <thead>
                    <tr>
                        <th style="width: 50px">STT</th>
                        <th style="width: 120px">Thumbnail</th>
                        <th>Title</th>
                        <th>Address</th>
                        <th>Price</th>
                        <th>Tour Date</th>
                        <th style="width: 50px"></th>
                        <th style="width: 50px"></th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${tourList}" var="tour" varStatus="loop">
                        <tr>
                            <td>${loop.index + 1}</td>
                            <td><img src="${tour.thumbnail}" style="width: 120px"/></td>
                            <td>${tour.title}</td>
                            <td>${tour.address}</td>
                            <td>${tour.dateTime}</td>
                            <td>${tour.price}</td>
                            <td>
                                <button class="btn btn-warning">Edit</button>
                            </td>
                            <td>
                                <button class="btn btn-danger">Delete</button>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </body>
</html>


#index-new.jsp


<%-- 
    Document   : index
    Created on : Aug 3, 2022, 8:42:49 AM
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Tour List</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align: center">Tour List</h1>
            <a href="add.html"><button class="btn btn-success" style="margin-bottom: 20px">Add new tour</button></a>
            <table class="table table-hovered">
                <thead>
                    <tr>
                        <th style="width: 50px">STT</th>
                        <th style="width: 120px">Thumbnail</th>
                        <th>Title</th>
                        <th>Address</th>
                        <th>Price</th>
                        <th>Tour Date</th>
                        <th style="width: 50px"></th>
                        <th style="width: 50px"></th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${tourList}" var="item" varStatus="loop">
                        <tr>
                            <td>${loop.index + 1}</td>
                            <td><img src="${item.tour.thumbnail}" style="width: 120px"/></td>
                            <td>${item.tour.title}</td>
                            <td>${item.tour.address}</td>
                            <td>${item.tour.price}</td>
                            <td>${item.tourDateEx}</td>
                            <td>
                                <button class="btn btn-warning">Edit</button>
                            </td>
                            <td>
                                <button class="btn btn-danger">Delete</button>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </body>
</html>


Tags:

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

5

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