Java Today
J2SE, J2EE information blog including: Spring, Servlets, JSP, etc.
Thursday, September 15, 2016
Tuesday, July 5, 2016
Spring and RESTful webservice Integration
Spring and RESTful webservice Integration
Earlier, we had developed an application using Spring and Rest. But, this is a basic app which shows integration of Spring with Rest at a beginner level. This demo app is for freshers.
Following below steps to create this application:
1) Libraries required:
spring-core 4.1.6 RELEASE
spring-web 4.1.6 RELEASE
spring-webmvc 4.1.6 RELEASE
jstl 1.2
2) Create a xml file named as web.xml in WEB-INF folder and write following code:
<!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>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3) Create a xml file named as springrest-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.controller" />
</beans>
4) Create a package named as com.gag.controller and Create a class named as SpringRestController.java and write following code in it:
package com.gag.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class SpringRestController {
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String hello(@PathVariable String name) {
String result = "Hello " + name;
return result;
}
}
5) Create a JSP or any html file and write following code in it:
<html>
<body>
<a href="hello/Gagan">Say Hello</a>
</body>
</html>
Our output would be like as below:
This is an anchor tag on which you would click and a Hello Message is shown:
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>
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>
Thursday, June 23, 2016
RESTful WebService using Jersey, AngularJS, MySQL (Small application to maintain users - Usermaintenance)
RESTful WebService using Jersey, AngularJS, MySQL
In this application, we will use AngularJS at the front-end and MySQL at the back-end. Moreover, Angular will communicate with database to store and fetch information using RESTful webservices. Obviously, we would be using JSON format for transfer of data from angular to rest and vice versa.
Following some steps to achieve this task and our output will be as below:
a) Libraries required:
jersey-server 1.9
mysql-connector-java 5.1.10
(com.google.code.gson) gson 2.2.1
b) Create a property file named as configuration.properties and write following lines:
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///um
jdbc.user = root
c) Create a package named as com.gag and Create a class named as ReadFromPropertiesFile.java and write following lines in it:
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 "";
}
}
d) Create a class named as ConnectDB.java and write following lines in it:
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) {
System.out.println("ConnectDB: " + e);
Logger.getLogger(ConnectDB.class + "");
}
return conn;
}
}
e) Create a POJO class named as Customer.java and write following lines in it:
package com.gag;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
private int id;
private String name, email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "{\"id\":\"" + id + "\",\"name\":\"" + name + "\",\"email\":\""
+ email + "\"}";
}
}
f) Create a class CustomerServices.java and write following lines 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");
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 "{\"msg\":\"Customer Created\"}";
}
} catch (Exception e) {
System.out.println("addCustomer: " + e);
}
return "{\"msg\":\"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 "{\"msg\":\"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 "{\"msg\":\"Customer Deleted\"}";
}
} catch (Exception e) {
System.out.println("delCustomer: " + e);
}
return "Failed to Delete Customer";
}
}
g) Create a class named as CustomerAPI.java in which we will write our RESTful webservice code:
package com.gag;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
@Path("/customer")
public class CustomerAPI {
@GET
@Path("/getCustomers")
@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();
System.out.println(gson.toJson(lstCustomers));
feeds = gson.toJson(lstCustomers);
} catch (Exception e) {
System.out.println("Exception Error"); // Console
}
return feeds;
}
@POST
@Path("/addCustomer")
@Produces(MediaType.APPLICATION_JSON)
public Response createCustomer(Customer customer) {
System.out.println();
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.addCustomer(customer);
} catch (Exception e) {
System.out.println("Exception Error " + e); // Console
}
return Response.status(200).entity(result).build();
}
@PUT
@Path("/updateCustomer/id/{id}/name/{name}/email/{email}")
public String updateCustomer(@PathParam("id") int id,
@PathParam("name") String name, @PathParam("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 result;
}
@DELETE
@Path("/delCustomer/id/{id}")
public String delCustomer(@PathParam("id") int id) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.delCustomer(id);
} catch (Exception e) {
System.out.println("Exception Error " + e); // Console
}
return result;
}
}
h) Create a xml file named as web.xml 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>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.gag</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
i) In the last, to use this API, we need a client, so we will use angularjs along with jquery and html. Following is the code in index.jsp file or any html file you can create:
<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 = 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/updateCustomer/id/'
+ $scope.form.id
+ "/name/"
+ $scope.form.name
+ "/email/"
+ $scope.form.email;
} else {
method = "POST";
url = 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/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);
}, function errorCallback(response) {
alert("ERROE:: " + response);
});
};
$scope.removeEmployee = function(employee) {
$http(
{
method : 'DELETE',
url : 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/delCustomer/id/'
+ employee.id
}).then(function successCallback(response) {
_success(response);
}, function errorCallback(response) {
alert("ERROE:: " + 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 : 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/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">Usermaintenance</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">
<div class="panel-heading">
<span class="lead">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>
Subscribe to:
Posts (Atom)