-Tạo project File > New File > Other.. > Web > Dynamic Web Project
Đọc thêm ở bài viết này
RUN App:
CREATE DATABASE MyDatabase
========================SQL======================
create table Employee
(
id varchar(10) primary key,
name nvarchar(50),
[address] nvarchar(100),
email nvarchar(50)
)
Download Driver SQL Server Đọc thêm ở bài viết này
ConnectionFactory.java
Java Jsp/Servet 2017
package com.giaima.dbconnect; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionFactory { // static reference to itself private static ConnectionFactory instance = new ConnectionFactory(); String url = "jdbc:sqlserver://localhost;databaseName=MyDatabase;useUnicode=true;characterEncoding=UTF-8"; String user = "sa"; String password = "12345678"; String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // private constructor private ConnectionFactory() { try { Class.forName(driverClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static ConnectionFactory getInstance() { return instance; } public Connection getConnection() throws SQLException, ClassNotFoundException { Connection connection = DriverManager.getConnection(url, user, password); return connection; } // Test connection database // public static void main(String[] args) throws ClassNotFoundException, SQLException { // System.out.println(getInstance().getConnection()); // } }
Test connect thành công!
CrudDAO.java
Java Jsp/Servet 2017
package com.giaima.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.giaima.dbconnect.ConnectionFactory; import com.giaima.model.Employee; public class CrudDAO { private Connection conn; private PreparedStatement pstmt; private ResultSet rs; private static Connection getConnection() throws SQLException, ClassNotFoundException { Connection con = ConnectionFactory.getInstance().getConnection(); return con; } public String insertEmployee(Employee empl) { String b = "true"; String sql = "INSERT INTO Employee VALUES(?,?,?,?)"; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, empl.getId()); pstmt.setString(2, empl.getName()); pstmt.setString(3, empl.getAddress()); pstmt.setString(4, empl.getEmail()); pstmt.executeUpdate(); } catch (SQLException | ClassNotFoundException e) { b = e.getMessage(); //Return string vể ajax đưa ra cảnh báo lỗi SQL cho Client } finally { try { if (pstmt != null) { pstmt.close();//Phần này liên quan tới insert nhiều lần bằng vòng lặp tôi chưa đề cập } if (conn != null) { conn.close();//Phần này liên quan tới conn.rollback() về ban đầu coi như không có lần thực hiện nào với Database thành công tôi chưa đề cập } } catch (SQLException e) { b = e.getMessage(); e.printStackTrace(); } } return b; } }
addEmployee.java
Java Jsp/Servet 2017
package com.giaima.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.giaima.dao.CrudDAO; import com.giaima.model.Employee; /** * Servlet implementation class addEmployee */ @WebServlet("/addEmployee") public class addEmployee extends HttpServlet { private static final long serialVersionUID = 1L; public addEmployee() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); String name = request.getParameter("name"); String address = request.getParameter("address"); String email = request.getParameter("email"); CrudDAO dao = new CrudDAO(); Employee empl = new Employee(id, name, address, email); String b = dao.insertEmployee(empl); if ("true".equals(b)) { PrintWriter out = response.getWriter(); response.setContentType("application/json"); out.write("{\"check\":\"true\"}"); out.flush();//Đưa chuỗi json này về Ajax để thực hiện hành vi check true } else { PrintWriter out = response.getWriter(); response.setContentType("application/json"); out.write("{\"check\":\"" + b + "\"}"); out.flush();//Đưa chuỗi Json này về Ajax để thực hiện hiển thị cảnh báo lỗi SQL cho Client } } }
Employee.java
Java Jsp/Servet 2017
package com.giaima.model; public class Employee { private String id; private String name; private String address; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Employee(String id, String name, String address, String email) { super(); this.id = id; this.name = name; this.address = address; this.email = email; } public Employee() { super(); } }
index.jsp
Java Jsp/Servet 2017
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>Add Employee</title> <script src="js/jquery-1.10.0.js"></script>//Cần có để chương trình hiểu và chạy được ngôn ngữ Jquery vs ajax <script src="js/ajaxEmployee.js"></script> </head> <body> <p id="message" align="left" ></p> //Hiển thị thông báo <form id="addForm" > <input type="text" id="id" name="id"/>ID<br/> <input type="text" id="name" name="name"/>Name<br/> <input type="text" id="address" name="address"/>Address<br/> <input type="text" id="email" name="email"/>Email<br/> <input type="button" class="add" value="ADD"/> </form> </body> </html>
ajaxEmployee.js
Java Jsp/Servet 2017
$(function () {
$('.add').click(function () {
var formData = $("#addForm").serialize(); //Lấy tất cả data trong form
$.ajax({
type: "POST", //với servlet thì sẽ đi vào method doPost
url: "addEmployee", //Tên của class Servlet
cache: false,
data: formData,
success: function (result) {
if (result.check == "true") {
$('#message').text("Insert Success!"); //Ghi value vào id message
$('#message').css('color', 'blue');
} else {
$('#message').text(result.check); //Ghi cảnh báo lỗi vào id message
$('#message').css('color', 'red');
}
}
});
});
});
Note: Các bạn nhớ download hỗ trợ chạy Jquery: jquery-1.10.0.jsRUN App:
0 nhận xét:
Post a Comment