• Thế Giới Giải Mã

    Bí ẩn nhân loại Leonardo Da Vinci

  • Thế Giới Giải Mã

    Anh hùng thầm lặng Nikola Tesla

  • Thế Giới Giải Mã

    Thần đèn Thomas Edison

  • Thế Giới Giải Mã

    Người thôi miên Adolf Hitler

Showing posts with label Spring Boot. Show all posts
Showing posts with label Spring Boot. Show all posts

21 October 2018

Spring Boot CRUD Restful + HashMap + AngularJS + Eclipse Spring

Công nghệ
Spring v2.0.6
Java 8
Create Project

Cấu trúc Project
pom.xml
Spring Boot 2018
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.example</groupId>
   <artifactId>spring-boot-helloworld-thymeleaf</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>spring-boot-helloworld-thymeleaf</name>
   <description>Demo project for Spring Boot</description>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.0.RELEASE</version>
      <relativePath />
      <!-- lookup parent from repository -->
   </parent>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.dataformat</groupId>
         <artifactId>jackson-dataformat-xml</artifactId>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>
MainController.java
Spring Boot 2018
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {

   @RequestMapping("/")
   public String welcome() {
      return "index";
   }
}
Spring Boot Restful
MainRESTController.java
Spring Boot 2018
package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.EmployeeDAO;
import com.example.demo.model.Employee;
import com.example.demo.model.EmployeeForm;
import com.example.demo.model.Welcome;

@RestController
public class MainRESTController {

   @Autowired
   private EmployeeDAO employeeDAO;

   // http://localhost:8080/employees
   @RequestMapping(value = "/employees",
      method = RequestMethod.GET,
      produces = {
         MediaType.APPLICATION_JSON_VALUE,
         /*MediaType.APPLICATION_XML_VALUE*/
      })
   @ResponseBody
   public List < Employee > getEmployees() {
      List < Employee > list = employeeDAO.getAllEmployees();
      System.out.println("Get employee");
      return list;
   }

   // http://localhost:8080/employee/{empId}
   @RequestMapping(value = "/employee/{empId}",
      method = RequestMethod.GET,
      produces = {
         MediaType.APPLICATION_JSON_VALUE,
         /*MediaType.APPLICATION_XML_VALUE*/
      })
   @ResponseBody
   public Employee getEmployee(@PathVariable("empId") Long empId) {
      return employeeDAO.getEmployee(empId);
   }

   // http://localhost:8080/employee
   @RequestMapping(value = "/employee",
      method = RequestMethod.POST,
      produces = {
         MediaType.APPLICATION_JSON_VALUE,
         /*MediaType.APPLICATION_XML_VALUE*/
      })
   @ResponseBody
   public Employee addEmployee(@RequestBody EmployeeForm empForm) {
      System.out.println("(Service Side) Creating employee with empNo: " + empForm.getEmpNo());
      return employeeDAO.addEmployee(empForm);
   }

   // http://localhost:8080/employee
   @RequestMapping(value = "/employee",
      method = RequestMethod.PUT,
      produces = {
         MediaType.APPLICATION_JSON_VALUE,
         /*MediaType.APPLICATION_XML_VALUE*/
      })
   @ResponseBody
   public Employee updateEmployee(@RequestBody EmployeeForm empForm) {
      System.out.println("(Service Side) Editing employee with Id: " + empForm.getEmpId());
      return employeeDAO.updateEmployee(empForm);
   }

   // http://localhost:8080/employee/{empId}
   @RequestMapping(value = "/employee/{empId}",
      method = RequestMethod.DELETE,
      produces = {
         MediaType.APPLICATION_JSON_VALUE,
         /*MediaType.APPLICATION_XML_VALUE */
      })
   @ResponseBody
   public void deleteEmployee(@PathVariable("empId") Long empId) {
      System.out.println("(Service Side) Deleting employee with Id: " + empId);
      employeeDAO.deleteEmployee(empId);
   }

   // http://localhost:8080/welcome/user?name=Antonio
   // http://localhost:8080/welcome/user
   @RequestMapping(value = "/welcome/use",
      method = RequestMethod.GET,
      produces = {
         MediaType.APPLICATION_JSON_VALUE,
         /*MediaType.APPLICATION_XML_VALUE */
      })
   @ResponseBody
   public Welcome welcomeUser(@RequestParam(name = "name", required = false, defaultValue = "Java Test") String name) {
      return new Welcome(String.format("Welcome Mr. %s!", name));
   }
}
Dummy Data
EmployeeDAO.java
Spring Boot 2018
package com.example.demo.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import com.example.demo.model.Employee;
import com.example.demo.model.EmployeeForm;

@Repository
public class EmployeeDAO {
   private static final Map < Long, Employee > empMap = new HashMap < Long, Employee > ();

   static {
      initEmps();
   }

   private static void initEmps() {
      Employee emp1 = new Employee(1 L, "E01", "Smith", "Clerk");
      Employee emp2 = new Employee(2 L, "E02", "Allen", "Salesman");
      Employee emp3 = new Employee(3 L, "E03", "Jones", "Manager");

      empMap.put(emp1.getEmpId(), emp1);
      empMap.put(emp2.getEmpId(), emp2);
      empMap.put(emp3.getEmpId(), emp3);
   }

   public Long getMaxEmpId() {
      Set < Long > keys = empMap.keySet();
      Long max = 0 L;
      for (Long key: keys) {
         if (key > max) {
            max = key;
         }
      }
      return max;
   }

   public Employee getEmployee(Long empId) {
      return empMap.get(empId);
   }

   public Employee addEmployee(EmployeeForm empForm) {
      Long empId = this.getMaxEmpId() + 1;
      empForm.setEmpId(empId);
      Employee newEmp = new Employee(empForm);

      empMap.put(newEmp.getEmpId(), newEmp);
      return newEmp;
   }

   public Employee updateEmployee(EmployeeForm empForm) {
      Employee emp = this.getEmployee(empForm.getEmpId());
      if (emp != null) {
         emp.setEmpNo(empForm.getEmpNo());
         emp.setEmpName(empForm.getEmpName());
         emp.setPosition(empForm.getPosition());
      }
      return emp;
   }

   public void deleteEmployee(Long empId) {
      empMap.remove(empId);
   }

   public List < Employee > getAllEmployees() {
      Collection < Employee > c = empMap.values();
      List < Employee > list = new ArrayList < Employee > ();
      list.addAll(c);
      return list;
   }
}
Models
Employee.java
Spring Boot 2018
package com.example.demo.model;

public class Employee {
   private Long empId;
   private String empNo;
   private String empName;
   private String position;

   public Employee() {
      super();
   }

   public Employee(Long empId, String empNo, String empName, String position) {
      super();
      this.empId = empId;
      this.empNo = empNo;
      this.empName = empName;
      this.position = position;
   }

   public Employee(EmployeeForm empForm) {
      this.empId = empForm.getEmpId();
      this.empNo = empForm.getEmpNo();
      this.empName = empForm.getEmpName();
      this.position = empForm.getPosition();
   }

   public Long getEmpId() {
      return empId;
   }

   public void setEmpId(Long empId) {
      this.empId = empId;
   }

   public String getEmpNo() {
      return empNo;
   }

   public void setEmpNo(String empNo) {
      this.empNo = empNo;
   }

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getPosition() {
      return position;
   }

   public void setPosition(String position) {
      this.position = position;
   }
}
EmployeeForm.java
Spring Boot 2018
package com.example.demo.model;

public class EmployeeForm {

   private Long empId;
   private String empNo;
   private String empName;
   private String position;
   public EmployeeForm() {
      super();
   }
   public EmployeeForm(Long empId, String empNo, String empName, String position) {
      super();
      this.empId = empId;
      this.empNo = empNo;
      this.empName = empName;
      this.position = position;
   }
   public Long getEmpId() {
      return empId;
   }
   public void setEmpId(Long empId) {
      this.empId = empId;
   }
   public String getEmpNo() {
      return empNo;
   }
   public void setEmpNo(String empNo) {
      this.empNo = empNo;
   }
   public String getEmpName() {
      return empName;
   }
   public void setEmpName(String empName) {
      this.empName = empName;
   }
   public String getPosition() {
      return position;
   }
   public void setPosition(String position) {
      this.position = position;
   }
}
Welcome.java
Spring Boot 2018
package com.example.demo.model;

public class Welcome {

   public Welcome(String message) {
      super();
      this.message = message;
   }

   private final String message;

   public String getMessage() {
      return message;
   }
}
AngularJS
main.js
Spring Boot 2018
var app = angular.module("EmployeeManagement", []);

app.controller("EmployeeController", function ($scope, $http) {

   $scope.employees = [];
   $scope.employeeForm = {
      empId: 1,
      empNo: "",
      empName: ""
   };

   // Now load the data from server
   _refreshEmployeeData();

   // HTTP POST/PUT methods for add/edit employee  
   // Call: http://localhost:8080/employee
   $scope.submitEmployee = function () {

      var method = "";
      var url = "";

      if ($scope.employeeForm.empId == -1) {
         method = "POST";
         url = '/employee';
      } else {
         method = "PUT";
         url = '/employee';
      }

      $http({
         method: method,
         url: url,
         data: angular.toJson($scope.employeeForm),
         headers: {
            'Content-Type': 'application/json'
         }
      }).then(_success, _error);
   };

   $scope.createEmployee = function () {
      _clearFormData();
   }

   // HTTP DELETE- delete employee by Id
   // Call: http://localhost:8080/employee/{empId}
   $scope.deleteEmployee = function (employee) {
      $http({
         method: 'DELETE',
         url: '/employee/' + employee.empId
      }).then(_success, _error);
   };

   // In case of edit
   $scope.editEmployee = function (employee) {
      $scope.employeeForm.empId = employee.empId;
      $scope.employeeForm.empNo = employee.empNo;
      $scope.employeeForm.empName = employee.empName;
   };

   // Private Method  
   // HTTP GET- get all employees collection
   // Call: http://localhost:8080/employees
   function _refreshEmployeeData() {
      $http({
         method: 'GET',
         url: '/employees'
      }).then(
         function (res) { // success
            $scope.employees = res.data;
         },
         function (res) { // error
            console.log("Error: " + res.status + " : " + res.data);
         }
      );
   }

   function _success(res) {
      _refreshEmployeeData();
      _clearFormData();
   }

   function _error(res) {
      var data = res.data;
      var status = res.status;
      var header = res.header;
      var config = res.config;
      alert("Error: " + status + ":" + data);
   }

   // Clear the form
   function _clearFormData() {
      $scope.employeeForm.empId = -1;
      $scope.employeeForm.empNo = "";
      $scope.employeeForm.empName = ""
   };
});
index.html
Spring Boot 2018
<!DOCTYPE html>
<html xmlns:th="http://wwwthymeleaf.org">
   <head>
      <meta charset="ISO-8859-1" />
      <title>AngularJS</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
      <script th:src="@{/main.js}"></script>
   </head>
   <body ng-app="EmployeeManagement" ng-controller="EmployeeController">
      <h3>CRUD: Spring Boot + Rest + AngularJS</h3>
      <form ng-submit="submitEmployee()">
         <table border="0">
            <tr>
               <td>Emp Id</td>
               <td>{{employeeForm.empId}}</td>
            </tr>
            <tr>
               <td>Emp No</td>
               <td><input type="text" ng-model="employeeForm.empNo" /></td>
            </tr>
            <tr>
               <td>Emp Name</td>
               <td><input type="text" ng-model="employeeForm.empName" /></td>
            </tr>
            <tr>
               <td colspan="2"><input type="submit" value="Submit"
                  class="blue-button" /></td>
            </tr>
         </table>
      </form>
      <br />
      <a class="create-button" ng-click="createEmployee()">Create
      Employee</a>
      <table border="1">
         <tr>
            <th>Emp Id</th>
            <th>Emp No</th>
            <th>Emp Name</th>
            <th>Edit</th>
            <th>Delete</th>
         </tr>
         <!-- $scope.employees -->
         <tr ng-repeat="employee in employees">
            <td>{{ employee.empId }}</td>
            <td>{{ employee.empNo }}</td>
            <td>{{ employee.empName }}</td>
            <td><a ng-click="editEmployee(employee)" class="edit-button">Edit</a>
            </td>
            <td><a ng-click="deleteEmployee(employee)" class="delete-button">Delete</a>
            </td>
         </tr>
      </table>
   </body>
</html>
application.properties
Spring Boot 2018
# THYMELEAF
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix = .html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=true

#server.port = 9195
Run demo
Rest: JSON


Cấu hình
Rest xml
<dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Update để eclipse tự động thêm thư viện mới vào project

 

BACK TO TOP

Xuống cuối trang