P1: Select
Tiếp tục >> phần này ta triển khai thêm chức năng Insert
Class DemoService
Java 2016
//add user
@RequestMapping(value="/addUser",method = RequestMethod.POST)
@Produces(MediaType.APPLICATION_JSON)
public String addUser(@RequestBody User user){
UserDAO userDAO = new UserDAO();
userDAO.addStudent(user);
return "Hello " + user.getName() + "\n" + "Age " + user.getAge();
}
Class UserDAO
Java 2016
public void addStudent(User user){
try {
stmt = conn.prepareStatement("INSERT INTO student.student (name, age) VALUES (?, ?)");
stmt.setString(1, user.getName());
stmt.setString(2, user.getAge());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
index.html
Java 2016
<!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Demo Hello WebService</title> </head> <body> <script> window.jQuery || document.write('<script src="jquery-1.12.0.min.js"><\/script>') </script> <script> (function($){ $(document).ready(function() { selectUser(); insertUser(); }); function selectUser(){ $.get("http://localhost:8080/viewAllUser", function(data){ $.each(data, function(key, value){ $(".Student").append("<p> Name: " + value.name + " </br> Age: " + value.age + "</p>"); }); }); } function insertUser(){ $("#save").click(function(){ var name = $("#name").val(); var age = $("#age").val(); var data = JSON.stringify({ "name": name, "age": age, }); $.ajax({ type: "POST", url: "http://localhost:8080/addUser", data: data, dataType: 'appLication/json', contentType: 'appLication/json', complete: function(){ $("#name").val(""); $("#age").val(""); location.reload(); } }); }); } })(jQuery); </script> <div class="Student"> <div class="name"></div> <div class="age"></div> </div> <div id="form-user">Insert: <input id="name" type="text" name="name" placeholder="Name"> <input id="age" type="number" name="age" placeholder="Age"> <button id="save" type="submit">Insert</button> </div> </body> </html>
Đóng chương trình nút x và ô vuông đỏ ở cửa số console và chạy lại!
Chạy file index.html
0 nhận xét:
Post a Comment