By GokiSoft.com| 09:36 19/12/2020|
Spring MVC

[Share Code] Tìm hiểu SpringMVC - Database - Lập trình Spring MVC BT2143



- Ket noi CSDL => Spring MVC

create table student (
	id int primary key auto_increment,
	name varchar(50) not null,
	email varchar(150),
	birthday date,
	password varchar(32),
	address varchar(200)
)




#editor.jsp


<%-- 
    Document   : editor
    Created on : Dec 12, 2020, 9:13:00 AM
    Author     : teacher
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Registation Form * Form Tutorial</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">Registation Form - Input Student's Detail Information</h2>
			</div>
			<div class="panel-body">
                            <form method="post" action="save.html">
				<div class="form-group">
				  <label for="usr">Name:</label>
                                  <input type="text" name="id" value="${student.id}" style="display: none;"/>
                                  <input required="true" type="text" class="form-control" id="usr" name="name" value="${student.name}"/>
				</div>
				<div class="form-group">
				  <label for="email">Email:</label>
                                  <input required="true" type="email" class="form-control" id="email" name="email" value="${student.email}"/>
				</div>
				<div class="form-group">
				  <label for="birthday">Birthday:</label>
                                  <input type="date" class="form-control" id="birthday" name="birthday" value="${student.birthdayStr}"/>
				</div>
				<div class="form-group">
				  <label for="pwd">Password:</label>
                                  <input required="true" type="password" class="form-control" id="pwd" name="password"/>
				</div>
				<div class="form-group">
				  <label for="confirmation_pwd">Confirmation Password:</label>
                                  <input required="true" type="password" class="form-control" id="confirmation_pwd" name="confirm_pwd"/>
				</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>
                                <a href="list.html"><button class="btn btn-warning" type="button">Back</button></a>
                            </form>
			</div>
		</div>
	</div>
</body>
</html>


#list.jsp


<%-- 
    Document   : list
    Created on : Dec 12, 2020, 9:12:47 AM
    Author     : teacher
--%>

<%@ 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 - Page</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 - Page</h2>
			</div>
			<div class="panel-body">
                            <table class="table table-hover table-bordered">
                                <thead>
                                    <tr>
                                        <th>STT</th>
                                        <th>Ten</th>
                                        <th>Email</th>
                                        <th>Ngay Sinh</th>
                                        <th>Dia Chi</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach items="#{studentList}" var="std" varStatus="loop">
                                        <tr>
                                            <td>${loop.index + 1}</td>
                                            <td>${std.name}</td>
                                            <td>${std.email}</td>
                                            <td>${std.birthdayStrVn}</td>
                                            <td>${std.address}</td>
                                            <th><a href="editor.html?id=${std.id}"><button class="btn btn-warning">Edit</button></a></th>
                                            <th><button class="btn btn-danger" onclick="deleteStudent(${std.id})">Delete</button></th>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>
                            <a href="editor.html"><button class="btn btn-success">Add Student</button></a>
			</div>
		</div>
	</div>
    
    <script>
        function deleteStudent(id) {
            var option = confirm("Ban co muon xoa sinh vien nay khong???")
            if(!option) {
                return;
            }
            
            $.post('delete.html', {
                'id': id
            }, function(data) {
                //code => sau khi server da tra du lieu ve cho client
                console.log(data)
//                location.reload()
            })
        }
    </script>
</body>
</html>


#view.jsp


<%-- 
    Document   : view
    Created on : Dec 12, 2020, 9:20:36 AM
    Author     : teacher
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <ul>
            <li>Name: ${student.name}</li>
            <li>Email ${student.email}</li>
            <li>Birthday: ${student.birthday}</li>
            <li>Password: ${student.password}</li>
            <li>Address: ${student.address}</li>
        </ul>
    </body>
</html>


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


#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 java.text.SimpleDateFormat;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author teacher
 */
@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.findByName", query = "SELECT s FROM Student s WHERE s.name = :name")
    , @NamedQuery(name = "Student.findByEmail", query = "SELECT s FROM Student s WHERE s.email = :email")
    , @NamedQuery(name = "Student.findByBirthday", query = "SELECT s FROM Student s WHERE s.birthday = :birthday")
    , @NamedQuery(name = "Student.findByPassword", query = "SELECT s FROM Student s WHERE s.password = :password")
    , @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;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "name")
    private String name;
    // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
    @Size(max = 150)
    @Column(name = "email")
    private String email;
    @Column(name = "birthday")
    @Temporal(TemporalType.DATE)
    private Date birthday;
    @Size(max = 32)
    @Column(name = "password")
    private String password;
    @Size(max = 200)
    @Column(name = "address")
    private String address;

    public Student() {
    }

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

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

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    public String getBirthdayStr() {
        if(birthday == null) {
            return "";
        }
        String bod = new SimpleDateFormat("yyyy-MM-dd").format(birthday);
        return bod;
    }
    
    public String getBirthdayStrVn() {
        if(birthday == null) {
            return "";
        }
        String bod = new SimpleDateFormat("dd/MM/yyyy").format(birthday);
        return bod;
    }

    @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 "entity.Student[ id=" + id + " ]";
    }
    
}


#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 aptech.controller;

import bean.StudentModel;
import entity.Student;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
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 teacher
 */
@Controller
@RequestMapping(value = "/student")
public class StudentController {
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String index(ModelMap modelMap) {
//        List<StudentModel> dataList = new ArrayList<>();
//        dataList.add(new StudentModel("Sinh vien a", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien b", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien c", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien d", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien e", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien f", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien g", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
//        dataList.add(new StudentModel("Sinh vien h", "a@gmail.com", "2000-02-09", "123", "322", "Ha Noi"));
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("SpringMVCExamplePU");
        EntityManager em = factory.createEntityManager();
        
        Query q = em.createNamedQuery("Student.findAll", Student.class);
        List<Student> dataList = q.getResultList();
        
        modelMap.put("studentList", dataList);
        
        return "student/list";
    }
    
    @RequestMapping(value = "/editor", method = RequestMethod.GET)
    public String view(@RequestParam Map<String, String> form, ModelMap modelMap) {
        Student std = new Student();
        
        if(form.containsKey("id")) {
            try {
                int id = Integer.parseInt(form.get("id"));
            
                EntityManagerFactory factory = Persistence.createEntityManagerFactory("SpringMVCExamplePU");
                EntityManager em = factory.createEntityManager();

                std = em.find(Student.class, id);
            } catch(Exception e) {
                std = new Student();
            }
        }
        
        modelMap.put("student", std);
        
        return "student/editor";
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@RequestParam Map<String, String> form, ModelMap modelMap) {
        //Lay du lieu tu Form gui len server
        int id = 0;
        try {
            id = Integer.parseInt(form.get("id"));
        } catch(Exception e) {
            e.printStackTrace();
        }
        String name = form.get("name");
        String email = form.get("email");
        String birthday = form.get("birthday");
        String password = form.get("password");
        String confirm_pwd = form.get("confirm_pwd");
        String address = form.get("address");
        Date birthdate = new Date();
        
        try {
            birthdate = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("SpringMVCExamplePU");
        EntityManager em = factory.createEntityManager();
        
        //check id > 0 => update
        if(id > 0) {
            //update
            Student stdFind = em.find(Student.class, id);
            
            em.getTransaction().begin();
            stdFind.setAddress(address);
            stdFind.setName(name);
            stdFind.setEmail(email);
            stdFind.setPassword(password);
            stdFind.setBirthday(birthdate);
            em.getTransaction().commit();
            
            return "redirect:list.html";
        }
        
        //check id = 0 => insert
        em.getTransaction().begin();
        
        Student std = new Student();
        std.setName(name);
        std.setAddress(address);
        std.setBirthday(birthdate);
        //Su dung ma hoa MD5 => custom md5 (md5(md5(std) + primary_key)), bcrypt (pass => gen rat nhieu ma khac nhau => laravel (64))
        std.setPassword(password);
        std.setEmail(email);
        
        em.persist(std);
        
        em.getTransaction().commit();
        
//        StudentModel std = new StudentModel(name, email, birthday, password, confirm_pwd, address);
//        System.out.println(std);
//        
//        //Truyen du lieu tu controller -> sang view
//        modelMap.put("student", std);
//        return "student/view";
        return "redirect:list.html";
    }
    
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(@RequestParam Map<String, String> form) {
        //delete Student
        
        if(form.containsKey("id")) {
            int id = Integer.parseInt(form.get("id"));
            
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("SpringMVCExamplePU");
            EntityManager em = factory.createEntityManager();
            
            Student stdFind = em.find(Student.class, id);
            
            if(stdFind != null) {
                em.getTransaction().begin();
                em.remove(stdFind);
                em.getTransaction().commit();
            }
        }
        
        return "redirect:list.html";
    }
}


Tags:

Liên kết rút gọn:

https://gokisoft.com/2143

Bình luận