20 July 2016

Web Service Java Spring Select to Database - Ajax json - jquery P1

Download import Maven project demo

Vui lòng kiểu tra phiên bản Java đang chạy trên máy bạn!


Download phần mềm Spring
Cài đặt và chạy tạo project mới 
New Project > Other > Exiting Maven Project
OK
class User
Java 2016
package com.example.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {
 @XmlElement(name = "name")
 private String name;

 @XmlElement(name = "age")
 private String age;

 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }
 public User() {
  super();
  // TODO Auto-generated constructor stub
 }
 public User(String name, String age) {
  this.name = name;
  this.age = age;
 }
}

Class DBUtils
Java 2016
package com.example.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtils {
 private static Connection connection = null;
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost:3306/student";
 static final String DB_USER = "root"; //user
 static final String DB_PASS = "1234567"; //pass

 public static Connection getConnection() {
  if (connection != null) {
   return connection;
  } else {
   try {
    Class.forName(JDBC_DRIVER);
    connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   } catch (SQLException e) {
    e.printStackTrace();
   }
   return connection;
  }
 }
}
Class DemoService
Java 2016
package com.example.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.User;

@CrossOrigin
@RestController
public class DemoService {

 private Connection conn;

 public DemoService() {
  conn = DBUtils.getConnection();
 }
 // view json
 @RequestMapping(value = "/viewAllUser", method = RequestMethod.GET)
 public List<User> viewAllUser() {
  UserDAO userDAO = new UserDAO();
  List<User> list = new ArrayList<User>(userDAO.getAllUser());
  return list;
 }
}
 Tạo database mysql với workbench
Create Database
Java 2016
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `age` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;



Class UserDAO
Java 2016
package com.example.service;

import java.lang.Thread.State;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;

import com.example.model.*;

public class UserDAO {
 private Connection conn;
 private PreparedStatement stmt;
 private ResultSet rs;

 public UserDAO() {
  conn = (Connection) DBUtils.getConnection();
 }

 public List<User> getAllUser() {
  List<User> list = new ArrayList<User>();
  try {
   stmt = conn.prepareStatement("SELECT * FROM student.student");
   rs = stmt.executeQuery();
   while (rs.next()) {
    User user = new User(rs.getString("name"), rs.getString("age"));
    list.add(user);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }
}
Tạo 1 file index.html
Tất nhiên là html chạy kết hợp với : jquery-1.12.0.min.jsAjax json
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() {
     getUser();
    });
    function getUser(){
     $.get("http://localhost:8080/viewAllUser", function(data){
      $.each(data, function(key, value){
       $(".Student").append("<p> Name: " + value.name + " </br> Age: " + value.age + "</p>");
      });
     });
    }
   })(jQuery);
  </script>
        <div class="Student"> 
            <div class="name"></div>
            <div class="age"></div>
        </div> 
</body>
</html>
Chạy Spring Boot App để khởi động kết nối database và chạy service
Chạy thành công!
Chạy file index.html

Thành công select data từ mysql 'Successfully!'
P2: Insert

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang