Wednesday, June 29, 2016

RESTful webservice along with Spring 4 and AngularJS

In our earlier post, we developed a small application using REST and AngularJS. Follow this link for help http://techs4.blogspot.in/2016/06/restful-webservice-using-jersey.html Now, we are going to use Spring 4 to handle REST as it is used now a days in most IT-Software projects.

We would be using Spring Controller to handle REST request/response. In Spring 4, there is a new concept of @RestController Annotation.

Overview of our application:



Our front-end would look like as below:







Follow below steps to create this small application:

a) Libraries required:

jersey-server 1.9
mysql-connector-java 5.1.10
com.google.code.gson (gson) 2.2.1
spring-core 4.1.6
spring-web 4.1.6
spring-webmvc 4.1.6
javax.servlet-api 3.1.0

b) Create a xml file named as spring-servlet.xml in WEB-INF folder and write following code in it:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.gag" />

</beans>


c) Create another xml file named as web.xml in WEB-INF folder and write following code in it:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


d) Create a properties file named as configuration.properties and write following code in it:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///um
jdbc.user = root

e) Create a package named as com.gag and within this package Create a class (POJO) named as Customer.java in it:

package com.gag;

public class Customer {

private Integer id;
private String name, email;

public String getName() {
return name;
}

public Integer getId() {
return id;
}

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

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

public String getEmail() {
return email;
}

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


f) Create a class named as ReadFromPropertiesFile.java in which following code is to be written:


package com.gag;

import java.io.InputStream;
import java.util.Properties;

public class ReadFromPropertiesFile {

Properties properties = null;

ReadFromPropertiesFile() {
try {
InputStream is = ReadFromPropertiesFile.class.getClassLoader()
.getResourceAsStream("configuration.properties");
properties = new Properties();
properties.load(is);
} catch (Exception e) {
System.out.println("aaaa " + e);
}
}

public String getURL() {
try {
return properties.getProperty("jdbc.url");
} catch (Exception e) {
System.out.println("getURL:" + e);
}
return "";
}

}


g) Create another class named as ConnectDB.java in which database connectivity is performed:

package com.gag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;

public class ConnectDB {

static ReadFromPropertiesFile obj = new ReadFromPropertiesFile();

public static Connection connect() {

Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(obj.getURL(), "root", "");
} catch (Exception e) {
Logger.getLogger(ConnectDB.class + "");
}
return conn;
}
}

h) Create a service layer class named as CustomerServices.java and write following code in it:

package com.gag;

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

public class CustomerServices {

public List<Customer> getAllCustomers() {
List<Customer> lst = new ArrayList();
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("select * from customer order by id");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Customer obj = new Customer();
obj.setId(rs.getInt("id"));
obj.setName(rs.getString("name"));
obj.setEmail(rs.getString("email"));
lst.add(obj);
}
} catch (Exception e) {
System.out.println(e);
}
return lst;
}

public String addCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("insert into customer values(?,?,?)");
pstmt.setInt(1, obj.getId());
pstmt.setString(2, obj.getName());
pstmt.setString(3, obj.getEmail());
int i = pstmt.executeUpdate();
if (i > 0) {
return "Customer Created";
}
} catch (Exception e) {
System.out.println("addCustomer: " + e);
}
return "Failed to  Create Customer";
}

public String updateCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("update customer set name=?,email = ? where id = ?");
pstmt.setString(1, obj.getName());
pstmt.setString(2, obj.getEmail());
pstmt.setInt(3, obj.getId());
int i = pstmt.executeUpdate();
if (i > 0) {
return "Customer Updated";
}
} catch (Exception e) {
System.out.println("updateCustomer: " + e);
}
return "Failed to  Update Customer";
}

public String delCustomer(int id) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("delete from customer where id = ?");
pstmt.setInt(1, id);
int i = pstmt.executeUpdate();
if (i > 0) {
return "Customer Deleted";
}
} catch (Exception e) {
System.out.println("delCustomer: " + e);
}
return "Failed to  Delete Customer";
}
}


i) Create a class named as CustomerAPI.java and write following code in it:

package com.gag;

import java.util.List;

import javax.ws.rs.core.MediaType;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;

import com.google.gson.Gson;

@RestController
public class CustomerAPI {

@RequestMapping(value = "/getCustomers", method = RequestMethod.GET, produces = "application/json")
public String feed() {
String feeds = null;
try {
List<Customer> lstCustomers = null;
CustomerServices customerServices = new CustomerServices();
lstCustomers = customerServices.getAllCustomers();
Gson gson = new Gson();
feeds = gson.toJson(lstCustomers);
} catch (Exception e) {
System.out.println("Exception Error"); // Console
}
return feeds;
}

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
public ResponseEntity createCustomer(@RequestBody Customer obj) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.addCustomer(obj);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return new ResponseEntity(HttpStatus.CREATED);
}

@RequestMapping(value = "/updateCustomer/id/{id}/name/{name}/email/{email}", method = RequestMethod.PUT)
public ResponseEntity<String> updateCustomer(@PathVariable("id") int id,
@PathVariable("name") String name,
@PathVariable("email") String email) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
Customer obj = new Customer();
obj.setId(id);
obj.setName(name);
obj.setEmail(email);
result = customerServices.updateCustomer(obj);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return new ResponseEntity<String>(HttpStatus.CREATED);
}

@RequestMapping(value = "/delCustomer/id/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> delCustomer(@PathVariable("id") Integer id) {
if (id > 0) {
String result = "";
System.out.println("Id:: " + id);
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.delCustomer(id);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return new ResponseEntity<String>(HttpStatus.CREATED);
} else {
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
}
}


j) Create an index.jsp file and write following code in it:

<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script type="text/javascript">
var myapp = angular.module("myApp", []);

myapp.controller("umcontroller", function($scope, $http) {
$scope.employees = [];
$scope.form = {
id : "",
name : "",
email : ""
};
_refreshPageData();
$scope.check = "";
$scope.submitCustomer = function() {
if ($scope.form.check == "check") {
method = "PUT";
url = 'updateCustomer/id/' + $scope.form.id + "/name/"
+ $scope.form.name + "/email/" + $scope.form.email;
} else {
method = "POST";
url = 'addCustomer';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then(function successCallback(response) {
$scope.form.check = "";
_success(response);
});
};
$scope.removeEmployee = function(employee) {
$http({
method : 'DELETE',
url : 'delCustomer/id/' + employee.id
}).then(function successCallback(response) {
_success(response);
});
};
$scope.editEmployee = function(employee) {
$scope.form.name = employee.name;
$scope.form.email = employee.email;
$scope.form.id = employee.id;
$scope.form.check = "check";
};

function _refreshPageData() {
$http({
method : 'GET',
url : 'getCustomers'
}).then(function successCallback(response) {
$scope.employees = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}

function _success(response) {
_refreshPageData();
_clearForm()
}

function _error(response) {
console.log(response.statusText);
}

function _clearForm() {
$scope.form.name = "";
$scope.form.email = "";
$scope.form.id = "";
}

$scope.clearForm = function() {
_clearForm();
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="umcontroller">

<div class="generic-container" ng-controller="umcontroller">
<div class="panel panel-default">
<div class="panel-heading">
<span class="lead">User Registration Form </span>
</div>
<div class="formcontainer">
<form ng-submit="submitCustomer()">
<div class="row">
<input type="hidden" ng-model="form.id" /> <input type="hidden"
ng-model="form.check" />
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="id">Id</label>
<div class="col-md-7">
<input type="text" ng-model="form.id" name="id"
class="username form-control input-sm"
placeholder="Enter your Id" required ng-minlength="1" />

</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="name">Name</label>
<div class="col-md-7">
<input type="text" ng-model="form.name" id="name"
class="username form-control input-sm"
placeholder="Enter your name" required ng-minlength="3" />

</div>
</div>
</div>


<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="email">Email</label>
<div class="col-md-7">
<input type="text" ng-model="form.email" id="email" name="email"
class="form-control input-sm"
placeholder="Enter your Email [This field is validation free]" />
</div>
</div>
</div>



<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!form.check ? 'Add' : 'Update'}}"
class="btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="clearForm()"
class="btn-sm">Reset Form</button>
</div>
</div>

</form>
</div>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="lead">List of Users </span>
</div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Email</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in employees">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.name"></span></td>
<td><span ng-bind="u.email"></span></td>
<td>
<button type="button" ng-click="editEmployee(u)"
class="btn btn-success custom-width">Edit</button>
<button type="button" ng-click="removeEmployee(u)"
class="btn btn-danger custom-width">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

</body>
</html>