Restful Web Service

Creating Restful Web Services For CRUD Operations In Java With Spring 4.2.5 Using JDBCTemplate

As I mentioned in my last post i.e. “CREATING RESTFUL WEB SERVICES IN JAVA USING SPRING 4.2.5 FOR CRUD OPERATIONS(WITH MAVEN)” that we will do our
all database related operations later by using JDBCTemplte so let’s work on this today.

First lets talk about JDBCTemplate class of Spring framework.In our previous example you will see that there was a lot of code related to executing and querying database,when we were just using normal JDBC connection to our database.You will see there certain classes which I have written like:-
1)DBUtil.java and 2)SSBResultSet.java.

Below are some issue with mentioned approach :-
a)Lot of code needed like creating connection, statement, closing resultset, connection etc and duplication was code.
b)Exception handling was needed with database logic.
c)Transaction handling was needed.

For coming out of these issues Spring provided feature of JdbcTemplate which is powerful feature for connecting database and executing SQL queries.It internally uses same JDBC apis but removes lot of problems.

If you have gone through above mentioned previous post than you will be aware that we were able to successfully create web services for CRUD operations.

I am writing all the classes of code here.So that one not need necessarily go through the previous post.
So Lets create our application for CRUD web services from scratch.Again For this sample I am using My SQL as database.Lets Start step by step.

Step1 :-

Create database with name ‘companydetail’ which will be having the fields as below:-
You can directly run below script to create the sql database as per our sample.


CREATE SCHEMA 'companydetail' ;

CREATE TABLE 'companydetail'.'company' (
'companyId' INT NOT NULL AUTO_INCREMENT COMMENT '',
'name' VARCHAR(45) NOT NULL COMMENT '',
'ceo' VARCHAR(45) NOT NULL COMMENT '',
'country' VARCHAR(45)

NOT NULL COMMENT '',
'foundationYear' VARCHAR(45) NOT NULL COMMENT '',
'noOfEmployee' VARCHAR(45) NOT NULL COMMENT '',
PRIMARY KEY (`companyId`) COMMENT '');

Step2 :-
a)In Eclipse go to File >> New >> Maven Project.
b)Leave deault values as it is i.e. “maven-archetype-webapp” Under ArtifactId and then click on ‘Next’.
c)Under the group id name ‘com.ssb.webSample’ and Aritfact Id as ‘SpringMavenRestDemoService’.
d)Click on Finish.
You will be able to ‘SpringMavenRestDemoService’ application in your project list.

Step3:-Open the ‘pom.xml’ of ‘SpringMavenRestDemoService’ in text editor. And Replace it’s content with content below:-

<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/maven-v4_0_0.xsd">
   
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ssb.webSample</groupId>
  <artifactId>SpringMavenRestDemoService</artifactId>
  <packaging>war</packaging>
  <version>1.0.0</version>
  <name>SpringMavenRestDemoService</name>
  <url>http://maven.apache.org</url>
  <description>CURD Operations with SPRING for REST Services</description>
  
 <properties>
        <spring.version>4.2.5.RELEASE</spring.version>
        <jdk.version>1.7</jdk.version>
        <mysql.connector.java.version>5.1.38</mysql.connector.java.version>
        <log4j.version>1.2.17</log4j.version>
        <jackson.mapper.version>1.9.13</jackson.mapper.version>
 </properties>
  
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
    </dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
    </dependency>
    
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.java.version}</version>
    </dependency> 
    
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.2.5.RELEASE</version>
	</dependency>
    
    
    <dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>${log4j.version}</version>
	</dependency>
	<dependency>
    	<groupId>com.fasterxml.jackson.core</groupId>
    	<artifactId>jackson-databind</artifactId>
    	<version>2.6.5</version>
	</dependency>
  </dependencies>
 
  <build>
        <finalName>SpringMavenRestDemoService</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
   
</project>

After this press right mouse click on project. Than Click on “Maven” and Click on “Update Project” and update by clicking on OK button.

Step4:-
Now Lets configure ur configuration files as below:-
a)context.xml inside META-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true">
</Context>

b)web.xml inside ‘WEB-INF’:-

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xmlns="http://java.sun.com/xml/ns/javaee"
		 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
		 id="WebApp_ID"
		 version="3.0">

	<display-name>Archetype Created Web Application</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/rest-servlet.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>rest</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!--This Servlet mapping will handle all incoming requests -->
	<servlet-mapping>
		<servlet-name>rest</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

c)Again Create a servlet inside ‘WEB-INF’ with name ‘rest-servlet.xml’.

Its content is as below:-

<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.ssb.webSample.SpringMavenRestDemoService.controllers" />
<context:component-scan base-package="com.ssb.webSample.SpringMavenRestDemoService.config" />
<context:component-scan base-package="com.ssb.webSample.SpringMavenRestDemoService.data" />

	<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
		<property name="contentType" value="application/json"/>
	</bean>
 
</beans>

Step 5:-

Now create a folder ‘java’ inside ‘main’ folder,and create package ‘com.ssb.webSample.SpringMavenRestDemoService’.Now you will require to create below classes as per their package.Adding source code for those one by one.

a)ServiceController.java:-

package com.ssb.webSample.SpringMavenRestDemoService.controllers;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssb.webSample.SpringMavenRestDemoService.data.CompanyDAO;
import com.ssb.webSample.SpringMavenRestDemoService.model.Company;

/*
 * @author Shardul.Bartwal
 *
 */

/**
* ServiceController will be serving for all rest-full web client request.
*/
@RestController
public class ServiceController {

	 	@Autowired
	        private CompanyDAO companyDAO;

		@Autowired
		private View jsonView;

		private final String DATA_FIELD = &quot;data&quot;;
		private final String ERROR_FIELD = &quot;error&quot;;

		private static final Logger logger_c = Logger.getLogger(ServiceController.class);

		/**
		* Gets all companies.
		* @return the list of companies.
		*/
		@RequestMapping(value = &quot;/getcompanyall/&quot;, method = RequestMethod.GET)
		public ModelAndView getcompanyall() throws IOException
		{
			System.out.println(&quot;Inside getCompanyAll()&quot;);
			List&lt;Company&gt; companyList = null;

			try {
				companyList = companyDAO.list();
			} catch (Exception exception) {
				String errMsg = &quot;Error getting all companies.&quot;;
				return errorResponder(String.format(errMsg, exception.toString()));
			}
			logger_c.debug(&quot;Returing CompanyList: &quot; + companyList.toString());
			return new ModelAndView(jsonView, DATA_FIELD, companyList);
		 }

		/**
		* Get company by id.
		* @param companyId
		* @return the Company
		*/
		@RequestMapping(value = &quot;/getcompany/{companyId}&quot;, method = RequestMethod.GET)
		public ModelAndView getcompany(@PathVariable String companyId)
		{
			System.out.println(&quot;Inside getcompany()&quot;);
			Company company = null;
			try {
				company = companyDAO.get(companyId);
			} catch (Exception exception) {
				String errMsg = &quot;Error getting company.&quot;;
				return errorResponder(String.format(errMsg, exception.toString()));
			}
			logger_c.debug(&quot;Returing CompanyList For Single Company: &quot; + company.toString());
			return new ModelAndView(jsonView, DATA_FIELD, company);
		 }

		/**
		* Delete Company by companyId.
		* @param companyId
		* @return the Company
		*/
		@RequestMapping(value = &quot;/deletecompany/{companyId}&quot;, method = RequestMethod.GET)
		public ModelAndView deletecompany(@PathVariable String companyId)
		{
			System.out.println(&quot;Inside deletecompany()&quot;);
			String deleteMsg = &quot;&quot;;
			try {
				 companyDAO.delete(companyId);
				 deleteMsg = &quot;Deleted Successfully&quot;;
			} catch (Exception exception) {
				String errMsg = &quot;Error getting company.&quot;;
				return errorResponder(String.format(errMsg, exception.toString()));
			}
			logger_c.debug(&quot;Returing CompanyList For Single Company: &quot; + deleteMsg.toString());

			return new ModelAndView(jsonView, DATA_FIELD, deleteMsg);
		 }

		/**
		* Creates a new Company.
		* @param companyStr
		* @return the model and view
		*/
		@RequestMapping(value = { &quot;/createcompany/&quot; }, method = { RequestMethod.POST },headers = {&quot;Accept=application/json&quot;} )
		public ModelAndView createcompany(@RequestBody  String companyStr,HttpServletResponse httpResponse,WebRequest webRequest){
		System.out.println(&quot;Inside createcompany()&quot;+ companyStr);
		Company company = null;
		String successMsg;
		try {
			company = new ObjectMapper().readValue(companyStr, Company.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		logger_c.debug(&quot;Creating Company: &quot; + companyStr.toString());

		try {
			companyDAO.saveOrUpdate(company);
			successMsg = &quot;Company Saved Successfully.&quot;;
		} catch (Exception e) {
			String errMsg = &quot;Error creating new Company.&quot;;
			return errorResponder(String.format(errMsg, e.toString()));
		}

		httpResponse.setStatus(HttpStatus.CREATED.value());
		httpResponse.setHeader(&quot;Location&quot;, webRequest.getContextPath() + &quot;/createcompany/&quot; + company.name);
		return new ModelAndView(jsonView, DATA_FIELD, successMsg);
		}

		/**
		* Update a Company.
		* @param companyStr
		* @return the model and view
		*/
		@RequestMapping(value = { &quot;/updatecompany/&quot; }, method = { RequestMethod.POST }, headers = {&quot;Accept=application/json&quot;} )
		public ModelAndView updatecompany(@RequestBody String companyStr,HttpServletResponse httpResponse,WebRequest webRequest)
		{
			System.out.println(&quot;Inside updateCompany()&quot; + companyStr);
			Company company = null;
			String updateMsg = &quot;&quot;;
			try {
				company = new ObjectMapper().readValue(companyStr, Company.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			logger_c.debug(&quot;Updating Company: &quot; + companyStr.toString());

			try {
				companyDAO.saveOrUpdate(company);
				updateMsg = &quot;Updated Successfully.&quot;;
			} catch (Exception e) {
			String errMsg = &quot;Error in updating Company.&quot;;
			return errorResponder(String.format(errMsg, e.toString()));
		}

			httpResponse.setStatus(HttpStatus.OK.value());
			httpResponse.setHeader(&quot;Location&quot;, webRequest.getContextPath() + &quot;/updatecompany/&quot; + company.name);
			return new ModelAndView(jsonView, DATA_FIELD, updateMsg);
		}

		/**
		* Create an error REST response.
		* @param errMsg,error message
		* @return model and view
		*/
		private ModelAndView errorResponder(String errMsg) {
			return new ModelAndView(jsonView, ERROR_FIELD, errMsg);
}

}

b)AppConfiguration.java :-

package com.ssb.webSample.SpringMavenRestDemoService.config;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.ssb.webSample.SpringMavenRestDemoService.data.CompanyDAO;
import com.ssb.webSample.SpringMavenRestDemoService.data.CompanyDAOImplementation;

/*
 * @author Shardul.Bartwal
 *
 */

@Configuration
@EnableWebMvc
public class AppConfiguration extends WebMvcConfigurerAdapter{

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(&quot;com.mysql.jdbc.Driver&quot;);
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/companydetail");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");

        return dataSource;
    }

    @Bean
    public CompanyDAO getCompanyDAO() {
        return new CompanyDAOImplementation(getDataSource());
    }
}

c)CompanyDAO.java

package com.ssb.webSample.SpringMavenRestDemoService.data;

import java.util.List;

import com.ssb.webSample.SpringMavenRestDemoService.model.Company;

/*
 * @author Shardul.Bartwal
 *
 */

public interface CompanyDAO {

    public void saveOrUpdate(Company company);

    public void delete(String companyId);

    public Company get(String companyId);

    public List<Company> list();
}

d)CompanyDAOImplementation.java :-

package com.ssb.webSample.SpringMavenRestDemoService.data;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.ssb.webSample.SpringMavenRestDemoService.model.Company;

public class CompanyDAOImplementation implements CompanyDAO
{
	
	private JdbcTemplate jdbcTemplate;
	 
    public CompanyDAOImplementation(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
 
    @Override
    public void saveOrUpdate(Company company) {
    	if ((company.getCompanyId() != null ) && (company.getCompanyId() != "" ))
    	{
            // Update
            String sql = "UPDATE company SET name=?, ceo=?, country=?,foundationYear=?,noOfEmployee=? WHERE companyId=?";
            jdbcTemplate.update(sql, company.getName(), company.getCeo(),company.getCountry(), company.getFoundationYear(), company.getNoOfEmployee(),company.getCompanyId());
        }
    	else {
            // Insert
            String sql = "insert into company(name, ceo, country, foundationYear,noOfEmployee) VALUES (?, ?, ?, ?,?)";
            System.out.print(company.getName());
            jdbcTemplate.update(sql, company.getName(), company.getCeo(),company.getCountry(), company.getFoundationYear(), company.getNoOfEmployee());
        }
     
    }
 
    @Override
    public void delete(String companyId) {
    	 String sql = "DELETE FROM company WHERE companyId=?";
    	    jdbcTemplate.update(sql, companyId);
    }
 
    @Override
    public List<Company> list() {
    	String sql = "SELECT * FROM company";
        List<Company> listCompany = jdbcTemplate.query(sql, new RowMapper<Company>() {
     
            @Override
            public Company mapRow(ResultSet rs, int rowNum) throws SQLException {
            	Company company = new Company();
     
            	company.setCompanyId(rs.getString("companyId"));
            	company.setName(rs.getString("name"));
            	company.setCeo(rs.getString("ceo"));
            	company.setCountry(rs.getString("country"));
            	company.setFoundationYear(rs.getString("foundationYear"));
            	company.setNoOfEmployee(rs.getString("noOfEmployee"));
     
                return company;
            }
     
        });
     
        return listCompany;
    }
 
    @Override
    public Company get(String companyId) {
    	 String sql = "SELECT * FROM company WHERE companyId=" + companyId;
    	    return jdbcTemplate.query(sql, new ResultSetExtractor<Company>() {
    	 
    	        @Override
    	        public Company extractData(ResultSet rs) throws SQLException,
    	                DataAccessException {
    	            if (rs.next()) {
    	            	Company company = new Company();
    	                
    	            	company.setCompanyId(rs.getString("companyId"));
    	            	company.setName(rs.getString("name"));
    	            	company.setCeo(rs.getString("ceo"));
    	            	company.setCountry(rs.getString("country"));
    	            	company.setFoundationYear(rs.getString("foundationYear"));
    	            	company.setNoOfEmployee(rs.getString("noOfEmployee"));
    	     
    	                return company;
    	            }
    	            return null;
    	        }
    	 
    	    });
    }
}

e)Company.java :-

package com.ssb.webSample.SpringMavenRestDemoService.model;

/*
 * @author Shardul.Bartwal
 *
 */

public class Company {

	public String companyId;
	public String name;
	public String ceo;
	public String country;
	public String foundationYear;
	public String noOfEmployee;

	 public Company(){
	    }

		public Company(String companyId, String name, String ceo, String country,String foundationYear,String noOfEmployee) {
		    this.companyId = companyId;
		    this.name = name;
		    this.ceo = ceo;
		    this.country = country;
		    this.foundationYear = foundationYear;
		    this.noOfEmployee = noOfEmployee;
		}

		public String getCompanyId() {
			return companyId;
		}
		public void setCompanyId(String companyId) {
			this.companyId = companyId;
		}

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

		public String getCeo() {
			return ceo;
		}
		public void setCeo(String ceo) {
			this.ceo = ceo;
		}

		public String getCountry() {
			return country;
		}
		public void setCountry(String country) {
			this.country = country;
		}

		public String getFoundationYear() {
			return foundationYear;
		}
		public void setFoundationYear(String foundationYear) {
			this.foundationYear = foundationYear;
		}

		public String getNoOfEmployee() {
			return noOfEmployee;
		}
		public void setNoOfEmployee(String noOfEmployee) {
			this.noOfEmployee = noOfEmployee;
		}

}

That’s all done. Now if you will build and run the project and if all goes well you are ready with web-services for all CRUD operations.

You can test these multiple services with ‘Postman’.

I am also including the source code of a web application created with AngularJS which will be consuming these all web-services,you can use this to see the services in action.
Below is code for same:-
a)index.html :-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CRUD Operations in AngularJS</title>
 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
 
    <script src="app.js" type="text/javascript"></script>
</head>
<body data-ng-app="crudSampleApp" data-ng-controller="CompanyController">
<h1>Company Details</h1>
<form name="companyForm">
<table>
<tr>
<td>
                    CompanyName</td>
<td>
                    CEO</td>
<td>
                    Country</td>
<td>
                    FoundationYear</td>
<td>
                    NoOfEmployee</td>
</tr>
<tr data-ng-repeat="comp in Companies">
<td>
                    {{comp.name}}</td>
<td>
                    {{comp.ceo}}</td>
<td>
                    {{comp.country}}</td>
<td>
                    {{comp.foundationYear}}</td>
<td>
                    {{comp.noOfEmployee}}</td>
<td>
                    <input type="submit" id="Edit" value="Edit" data-ng-click="getCompany(comp)"/></td>
<td>
                    <input type="submit" id="Delete" value="Delete" data-ng-click="deletecompany(comp)"/></td>
</tr>
<tr>
<td>
                   Company Name</td>
<td>
                    <input type="text" data-ng-model="Company.name" required /></td>
</tr>
<tr>
<td>
                    CEO</td>
<td>
                    <input type="text" data-ng-model="Company.ceo" /></td>
</tr>
<tr>
<td>
                    Country</td>
<td>
                    <input type="text" data-ng-model="Company.country" /></td>
</tr>
<tr>
<td>
                    FoundationYear</td>
<td>
                    <input type="text" data-ng-model="Company.foundationYear" /></td>
</tr>
<tr>
<td>
                    NoOfEmployee</td>
<td>
                    <input type="text" data-ng-model="Company.noOfEmployee" /></td>
</tr>
<tr>
<td></td>
<td>
                    <input type="submit" value="Save" data-ng-click="createCompany(Company)" data-ng-disabled="companyForm.user.$dirty && companyForm.user.$invalid ||                      companyForm.Company.name.$dirty && companyForm.Company.name.$invalid"/>
                    <input type="submit" value="Update" data-ng-click="updateCompany(Company)"/>
                    <input type="reset" value="Clear"/></td>
</tr>
</table>
</form>
 
</body>
</html>

b)app.js:-

var crudSampleApp = angular.module('crudSampleApp', []);
 
crudSampleApp.controller('CompanyController', ['$scope', '$http',function($scope, $http){
 
    angular.element(document).ready(function () {
        $scope.getCompanyList();
        });
 
    //Get Company List
    $scope.getCompanyList = function()
    {
         $http({
            url: "http://localhost:8080/SpringMavenRestDemoService/getcompanyall/",
            method: 'GET',
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        $scope.Companies = data.data.data;
                }).catch(function (e) {
                        $scope.error = e +"Unable to load company list.";
        });
    };
 
    //Get Company.
    $scope.getCompany = function (Company) {
        $http({
        url: "http://localhost:8080/SpringMavenRestDemoService/getcompany/" + Company.companyId,
        method: 'GET',
        headers: { 'Content-Type': 'application/json;charset=utf-8' },
        dataType : "JSONP",
        }).then(function (data) {
                    $scope.Company = data.data.data;
            }).catch(function (e) {
                    $scope.error = e +"Unable to load company.";
    });
    };
 
    //Insert new Company.
    $scope.createCompany = function (Company) {
       $http({
            url: 'http://localhost:8080/SpringMavenRestDemoService/createcompany/',
            method: 'POST',
            data : Company,
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        alert("Company added successfully.");
                        $scope.getCompanyList();
                        clearUI();
            }).catch(function (e) {
                        $scope.error = e +"Unable to add company.";
        });
    };
 
    //Update Company.
     $scope.updateCompany = function (Company) {
            $http({
            url: 'http://localhost:8080/SpringMavenRestDemoService/updatecompany/',
            method: 'POST',
            data : Company,
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        alert("Company updated successfully.");
                        $scope.getCompanyList();
                        clearUI();
            }).catch(function (e) {
                        $scope.error = e +"Unable to update company.";
        });
        };
 
    //Delete Company.
    $scope.deletecompany = function (Company) {     
 
       $http({
            url: 'http://localhost:8080/SpringMavenRestDemoService/deletecompany/'+ Company.companyId,
            method: 'GET',
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        alert("Company deleted successfully.");
                        $scope.getCompanyList();
                        clearUI();
            }).catch(function (e) {
                        $scope.error = e +"Unable to delete company.";
        });
    };
 
    function clearUI() {
        $scope.Company.companyId = "";
        $scope.Company.name = "";
        $scope.Company.ceo = "";
        $scope.Company.country = "";
        $scope.Company.foundationYear = "";
        $scope.Company.noOfEmployee = "";
    };
 
}]);

Hope this will helpful for someone.

Creating Restful Web Services In Java Using Spring 4.2.5 for CRUD Operations(With Maven)

As I mentioned it by last post i.e. ‘CREATING RESTFUL WEB SERVICES IN JAVA USING SPRING 4.2.5‘ that we will keep extending this sample application so let go further and make web services for CURD operations.

For this sample I am using My SQL as database.Lets Start step by step.I am using simple JDBC in this sample application.In future we will do this by using jdbcTemplate.

Step1 :-

Create database with name ‘companydetail’ which will be having the fields as below:-
You can directly run below script to create the sql database as per our sample.

CREATE SCHEMA `companydetail` ;

CREATE TABLE `companydetail`.`company` (
`companyId` INT NOT NULL AUTO_INCREMENT COMMENT '',
`name` VARCHAR(45) NOT NULL COMMENT '',
`ceo` VARCHAR(45) NOT NULL COMMENT '',
`country` VARCHAR(45)

NOT NULL COMMENT '',
`foundationYear` VARCHAR(45) NOT NULL COMMENT '',
`noOfEmployee` VARCHAR(45) NOT NULL COMMENT '',
PRIMARY KEY (`companyId`) COMMENT '');

Step2 :-
a)In Eclipse go to File >> New >> Maven Project.
b)Leave deault values as it is i.e. “maven-archetype-webapp” Under ArtifactId and then click on ‘Next’.
c)Under the group id name ‘com.ssb.webSample’ and Aritfact Id as ‘SpringMavenRestDemoService’.
d)Click on Finish.
You will be able to ‘SpringMavenRestDemoService’ application in your project list.

Step3:- Open the ‘pom.xml’ of ‘SpringMavenRestDemoService’ in text editor. And Replace it’s content with content below:-

<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/maven-v4_0_0.xsd">
 
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ssb.webSample</groupId>
  <artifactId>SpringMavenRestDemoService</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMavenRestDemoService</name>
  <url>http://maven.apache.org</url>
  <description>CURD Operations with SPRING for REST Services</description>
 
 <properties>
        <spring.version>4.2.5.RELEASE</spring.version>
        <jdk.version>1.7</jdk.version>
        <mysql.connector.java.version>5.1.38</mysql.connector.java.version>
        <log4j.version>1.2.17</log4j.version>
        <jackson.mapper.version>1.9.13</jackson.mapper.version>
 </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
    </dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
    </dependency>
 
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.java.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.5</version>
    </dependency>
  </dependencies>
 
  <build>
        <finalName>SpringMavenRestDemoService</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>

After this press right mouse click on project. Than Click on “Maven” and Click on “Update Project” and update by clicking on OK button.

Step4:-
Now Lets configure ur configuration files as below:-
a)context.xml inside META-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true">
</Context>

b)web.xml inside ‘WEB-INF’.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns="http://java.sun.com/xml/ns/javaee"       xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"        id="WebApp_ID"          version="3.0">
 
    <display-name>Archetype Created Web Application</display-name>
 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/rest-servlet.xml</param-value>
    </context-param>
 
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <!--This Servlet mapping will handle all incoming requests -->
    <servlet-mapping>
        <servlet-name>rest</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

c)Again Create a servlet inside ‘WEB-INF’ with name ‘rest-servlet.xml’.

Its content is as below:-

<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.ssb.webSample.SpringMavenRestDemoService.controllers" />
<context:component-scan base-package="com.ssb.webSample.SpringMavenRestDemoService.services" />
 
    <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
        <property name="contentType" value="application/json"/>
    </bean>
 
</beans>

Step 5:-

Now create a folder ‘java’ inside ‘main’ folder,and create package ‘com.ssb.webSample.SpringMavenRestDemoService’.Now you will require to create below classes as per their package.Adding source code for those one by one.

a)ServiceController.java

package com.ssb.webSample.SpringMavenRestDemoService.controllers;
 
import java.io.IOException;
import java.util.List;
 
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.apache.log4j.Logger;
 
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssb.webSample.SpringMavenRestDemoService.model.Company;
import com.ssb.webSample.SpringMavenRestDemoService.services.CompanyService;
 
/*
 * @author Shardul.Bartwal
 *
 */
 
/**
* ServiceController will be serving for all rest-full web client request.
*/
@RestController
public class ServiceController {
 
        @Autowired
        public CompanyService companyService;
 
        @Autowired
        private View jsonView;
 
        private final String DATA_FIELD = "data";
        private final String ERROR_FIELD = "error";
 
        private static final Logger logger_c = Logger.getLogger(ServiceController.class);
 
        /**
        * Gets all companies.
        * @return the list of companies.
        */
        @RequestMapping(value = "/getcompanyall/", method = RequestMethod.GET)
        public ModelAndView getcompanyall()
        {
            System.out.println("Inside getCompanyAll()");
            List<Company> companyList = null;
            try {
                companyList = companyService.getCompanyList();
            } catch (Exception exception) {
                String errMsg = "Error getting all companies.";
                return errorResponder(String.format(errMsg, exception.toString()));
            }
            logger_c.debug("Returing CompanyList: " + companyList.toString());
            return new ModelAndView(jsonView, DATA_FIELD, companyList);
         }
 
        /**
        * Get company by id.
        * @param companyId
        * @return the Company
        */
        @RequestMapping(value = "/getcompany/{companyId}", method = RequestMethod.GET)
        public ModelAndView getcompany(@PathVariable String companyId)
        {
            System.out.println("Inside getcompany()");
            Company company = null;
            try {
                company = companyService.getCompany(companyId);
            } catch (Exception exception) {
                String errMsg = "Error getting company.";
                return errorResponder(String.format(errMsg, exception.toString()));
            }
            logger_c.debug("Returing CompanyList For Single Company: " + company.toString());
            return new ModelAndView(jsonView, DATA_FIELD, company);
         }
 
        /**
        * Delete Company by companyId.
        * @param companyId
        * @return the Company
        */
        @RequestMapping(value = "/deletecompany/{companyId}", method = RequestMethod.GET)
        public ModelAndView deletecompany(@PathVariable String companyId)
        {
            System.out.println("Inside deletecompany()");
            String deleteMsg = "";
            try {
                deleteMsg = companyService.deleteCompany(companyId);
            } catch (Exception exception) {
                String errMsg = "Error getting company.";
                return errorResponder(String.format(errMsg, exception.toString()));
            }
            logger_c.debug("Returing CompanyList For Single Company: " + deleteMsg.toString());
 
            return new ModelAndView(jsonView, DATA_FIELD, deleteMsg);
         }
 
        /**
        * Creates a new Company.
        * @param companyStr
        * @return the model and view
        */
        @RequestMapping(value = { "/createcompany/" }, method = { RequestMethod.POST },headers = {"Accept=application/json"} )
        public ModelAndView createcompany(@RequestBody  String companyStr,HttpServletResponse httpResponse,WebRequest webRequest){
        System.out.println("Inside createcompany()"+ companyStr);
        Company company = null;
        Company createdCompany;
        try {
            company = new ObjectMapper().readValue(companyStr, Company.class);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        logger_c.debug("Creating Company: " + companyStr.toString());
 
        try {
            createdCompany = companyService.createCompany(company);
        } catch (Exception e) {
            String errMsg = "Error creating new Company.";
            return errorResponder(String.format(errMsg, e.toString()));
        }
 
        httpResponse.setStatus(HttpStatus.CREATED.value());
        httpResponse.setHeader("Location", webRequest.getContextPath() + "/createcompany/" + company.name);
        return new ModelAndView(jsonView, DATA_FIELD, createdCompany.name);
        }
 
        /**
        * Update a Company.
        * @param companyStr
        * @return the model and view
        */
        @RequestMapping(value = { "/updatecompany/" }, method = { RequestMethod.POST }, headers = {"Accept=application/json"} )
        public ModelAndView updatecompany(@RequestBody String companyStr,HttpServletResponse httpResponse,WebRequest webRequest)
        {
            System.out.println("Inside updateCompany()" + companyStr);
            Company company = null;
            Company updatedCompany = null;
            try {
                company = new ObjectMapper().readValue(companyStr, Company.class);
            } catch (JsonParseException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
 
            logger_c.debug("Updating Company: " + companyStr.toString());
 
            try {
                updatedCompany = companyService.updateCompany(company);
            } catch (Exception e) {
            String errMsg = "Error in updating Company.";
            return errorResponder(String.format(errMsg, e.toString()));
        }
 
            httpResponse.setStatus(HttpStatus.OK.value());
            httpResponse.setHeader("Location", webRequest.getContextPath() + "/updatecompany/" + company.name);
            return new ModelAndView(jsonView, DATA_FIELD, updatedCompany);
        }
 
        /**
        * Create an error REST response.
        * @param errMsg,error message
        * @return model and view
        */
        private ModelAndView errorResponder(String errMsg) {
            return new ModelAndView(jsonView, ERROR_FIELD, errMsg);
}
 
}

b)DBUtil.java

package com.ssb.webSample.SpringMavenRestDemoService.data;
 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
import com.ssb.webSample.SpringMavenRestDemoService.model.Company;
 
 /*
 * @author Shardul.Bartwal
 *
 */
 
public class DBUtil {
 
    /**
    * Gets a Company.
    * @return companyArrayList with a single company.
    * @throws SQLException
    */
    public static Company getComapnyFromDB(String companyId) throws SQLException
    {
        Company company = new Company();
 
        ResultSet resultSet = SSBResultSet.getResultSet("select * from company where companyId = "+ companyId );
        while( resultSet.next() )
        {
            company.companyId = resultSet.getString("companyId");
            company.name = resultSet.getString("name");
            company.ceo = resultSet.getString("ceo");
            company.country = resultSet.getString("country");
            company.foundationYear = resultSet.getString("foundationYear");
            company.noOfEmployee = resultSet.getString("noOfEmployee");
        }
        SSBResultSet.closeAll();
        return company;
    }
 
    /**
    * Gets list of companies.
    * @return companyArrayList.
    * @throws SQLException
    */
    public static List<Company> getAllComapniesFromDB() throws SQLException
    {
        List<Company> companyArrayList = new ArrayList<Company>();
 
        ResultSet resultSet = SSBResultSet.getResultSet("select * from company");
        while( resultSet.next() )
        {
            Company company = new Company();
            company.companyId = resultSet.getString("companyId");
            company.name = resultSet.getString("name");
            company.ceo = resultSet.getString("ceo");
            company.country = resultSet.getString("country");
            company.foundationYear = resultSet.getString("foundationYear");
            company.noOfEmployee = resultSet.getString("noOfEmployee");
            companyArrayList.add(company);
        }
        SSBResultSet.closeAll();
        return companyArrayList;
    }
 
    /**
    * Delete a Company.
    * @return Message for Delete Operation.
    * @throws SQLException
    */
    public static String deleteComapnyFromDB(String companyId) throws SQLException
    {
        String msgToReturn = "";
 
        String sqlString = "delete from company where companyId = "+ companyId;
 
        int deleteStauts = SSBResultSet.deleteRecord(sqlString);
        SSBResultSet.closeAll();
 
        if(deleteStauts == 1)
            msgToReturn = "Company Deleted Successfully.";
        else
            msgToReturn = "Can not Delete.";
 
        return msgToReturn;
    }
 
    /**
    * Create Company.
    * @return company.
    * @throws SQLException
    */
    public static Company createCompany(Company company) throws SQLException
    {
        Company companyToReturn = null;
        String nameCompany = "'"+company.name+"'";
        String ceo = "'"+ company.ceo + "'";
        String country = "'"+ company.country + "'";
        String foundationYear = "'"+ company.foundationYear + "'";
        String noOfEmployee = "'"+ company.noOfEmployee + "'";
 
        String sqlString = "insert into company(name,ceo,country,foundationYear,noOfEmployee) values(" + nameCompany + "," + ceo + "," + country + "," + foundationYear + "," + noOfEmployee
        + ")";
 
        int insertStauts = SSBResultSet.insertRecord(sqlString);
        SSBResultSet.closeAll();
 
        if(insertStauts == 1)
        companyToReturn = company;
 
        return companyToReturn;
    }
 
    /**
    * Update company.
    * @return company.
    * @throws SQLException
    */
    public static Company updateCompany(Company company) throws SQLException
    {
        Company companyToReturn = null;
        int companyId = Integer.parseInt(company.companyId);
        String nameCompany = "'"+company.name+"'";
        String ceo = "'"+ company.ceo + "'";
        String country = "'"+ company.country + "'";
        String foundationYear = "'"+ company.foundationYear + "'";
        String noOfEmployee = "'"+ company.noOfEmployee + "'";
 
        String sqlString = "UPDATE company set name=" + nameCompany +", ceo=" + ceo +", country=" + country + ", foundationYear=" + foundationYear + ", noOfEmployee=" +noOfEmployee + "where companyId="+companyId;
 
        int updateStauts = SSBResultSet.updateRecord(sqlString);
        SSBResultSet.closeAll();
 
        if(updateStauts == 1)
            companyToReturn = company;
 
        return companyToReturn;
    }
 
}

c)SSBResultSet.java

package com.ssb.webSample.SpringMavenRestDemoService.data;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class SSBResultSet {
static Connection connection;
static Statement statement;
static ResultSet resultSet;
static PreparedStatement preparedStatement;
static int insertedRecord;
static int updatedRecord;
static int deletedRecord;
 
static String connectionString;
static String userId;
static String password;
 
/*
 * @author Shardul.Bartwal
 *
 */
    private static void connectDB()
    {
        // Change below three variables according to your database settings.
        connectionString = "jdbc:mysql://127.0.0.1:3306/companydetail";
        userId = "root";
        password = "admin";
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectionString, userId, password);
        }
        catch(ClassNotFoundException classNotFoundException)
        {
            classNotFoundException.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public static ResultSet getResultSet(String queryString)
    {
        connectDB();
        String sqlSelectQueryString = queryString;;
        try
        {
            statement= connection.createStatement();
            resultSet = statement.executeQuery(sqlSelectQueryString);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
 
        }
            return resultSet;
    }
 
    public static int insertRecord(String queryString)
    {
        connectDB();
        String sqlInsertQueryString = queryString;;
        try
        {
            statement= connection.createStatement();
            insertedRecord = statement.executeUpdate(sqlInsertQueryString);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
 
        }
            return insertedRecord;
    }
 
    public static int deleteRecord(String queryString)
    {
        connectDB();
        String sqlDeleteQueryString = queryString;;
        try
        {
            statement= connection.createStatement();
            deletedRecord = statement.executeUpdate(sqlDeleteQueryString);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
 
        }
            return deletedRecord;
    }
 
    public static int updateRecord(String queryString)
    {
        connectDB();
        String sqlUpdateQueryString = queryString;;
        try
        {
            statement= connection.createStatement();
            updatedRecord = statement.executeUpdate(sqlUpdateQueryString);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
 
        }
            return updatedRecord;
    }
 
    public static void closeAll()
    {
        if(resultSet != null)
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(statement != null)
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(connection !=null)
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(insertedRecord > -1)
            insertedRecord = -1;
    }
 
}

d)Company.java

package com.ssb.webSample.SpringMavenRestDemoService.model;;

/*
 * @author Shardul.Bartwal
 *
 */

public class Company {

	public String companyId;
	public String name;
	public String ceo;
	public String country;
	public String foundationYear;
	public String noOfEmployee;

}

e)CompanyService.java

package com.ssb.webSample.SpringMavenRestDemoService.services;

import java.sql.SQLException;
import java.util.List;

import org.springframework.stereotype.Service;

import com.ssb.webSample.SpringMavenRestDemoService.data.DBUtil;
import com.ssb.webSample.SpringMavenRestDemoService.model.Company;

 /*
 * @author Shardul.Bartwal
 *
 */

@Service
public class CompanyService {

	public Company createCompany(Company company) throws SQLException
	{
		Company createdcompany = DBUtil.createCompany(company);
		return createdcompany;
	}

	public Company updateCompany(Company company) throws SQLException
	{
		Company updatedcompany = DBUtil.updateCompany(company);
		return updatedcompany;
	}

	public Company getCompany(String companyId) throws SQLException
	{
		Company company = DBUtil.getComapnyFromDB(companyId);
		return company;
	}

	public List<Company> getCompanyList() throws SQLException
	{
		List<Company> companiesList = DBUtil.getAllComapniesFromDB();
		return companiesList;
	}

	public String deleteCompany(String companyId) throws SQLException
	{
		String deleteMsgToReturn = DBUtil.deleteComapnyFromDB(companyId);
		return deleteMsgToReturn;
	}

}

That’s all done. Now if you will build and run the project and if all goes well you are ready with web-services for all CURD operations.

You can test these multiple services with ‘Postman’.

I am also including the source code a web application created with AngularJS which will be consuming these all web-services,you can use this to see the services in action.
Below is code for same:-
a)index.html :-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CURD Operations in AngularJS</title>
     
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
  
    <script src="app.js" type="text/javascript"></script>
</head>
<body data-ng-app="crudSampleApp" data-ng-controller="CompanyController">
<h1>Company Details</h1>
    <form name="companyForm">
        <table>
            <tr>
                <td>
                    CompanyName
                </td>
                <td>
                    CEO
                </td>
                <td>
                    Country
                </td>
                <td>
                    FoundationYear
                </td>
                <td>
                    NoOfEmployee
                </td>
            </tr>
            <tr data-ng-repeat="comp in Companies">
                <td>
                    {{comp.name}}
                </td>
                <td>
                    {{comp.ceo}}
                </td>
                <td>
                    {{comp.country}}
                </td>
                <td>
                    {{comp.foundationYear}}
                </td>
                <td>
                    {{comp.noOfEmployee}}
                </td>
                <td>
                    <input type="submit" id="Edit" value="Edit" data-ng-click="getCompany(comp)"/>
                </td>
                <td>
                    <input type="submit" id="Delete" value="Delete" data-ng-click="deletecompany(comp)"/>
                </td>
            </tr>
            <tr>
                <td>
                   Company Name
                </td>
                <td>
                    <input type="text" data-ng-model="Company.name" required />
                </td>
            </tr>
            <tr>
                <td>
                    CEO
                </td>
                <td>
                    <input type="text" data-ng-model="Company.ceo" />
                </td>
            </tr>
            <tr>
                <td>
                    Country
                </td>
                <td>
                    <input type="text" data-ng-model="Company.country" />
                </td>
            </tr>
            <tr>
                <td>
                    FoundationYear
                </td>
                <td>
                    <input type="text" data-ng-model="Company.foundationYear" />
                </td>
            </tr>
            <tr>
                <td>
                    NoOfEmployee
                </td>
                <td>
                    <input type="text" data-ng-model="Company.noOfEmployee" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <input type="submit" value="Save" data-ng-click="createCompany(Company)" data-ng-disabled="companyForm.user.$dirty && companyForm.user.$invalid ||
                     companyForm.Company.name.$dirty && companyForm.Company.name.$invalid"/>
                    <input type="submit" value="Update" data-ng-click="updateCompany(Company)"/>
                    <input type="reset" value="Clear"/>
                </td>
            </tr>
        </table>
    </form>   
</body>
</html>

b)app.js:-

var crudSampleApp = angular.module('crudSampleApp', []);
   
crudSampleApp.controller('CompanyController', ['$scope', '$http',function($scope, $http){
   
    angular.element(document).ready(function () {
        $scope.getCompanyList();
        });
   
    //Get Company List
    $scope.getCompanyList = function()
    {
         $http({
            url: "http://localhost:8080/SpringMavenRestDemoService/getcompanyall/",
            method: 'GET',
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        $scope.Companies = data.data.data;
                }).catch(function (e) {
                        $scope.error = e +"Unable to load company list.";
        });
    };
   
    //Get Company.
    $scope.getCompany = function (Company) {
        $http({
        url: "http://localhost:8080/SpringMavenRestDemoService/getcompany/" + Company.companyId,
        method: 'GET',
        headers: { 'Content-Type': 'application/json;charset=utf-8' },
        dataType : "JSONP",
        }).then(function (data) {
                    $scope.Company = data.data.data;
            }).catch(function (e) {
                    $scope.error = e +"Unable to load company.";
    });
    };
   
    //Insert new Company.
    $scope.createCompany = function (Company) {
       $http({
            url: 'http://localhost:8080/SpringMavenRestDemoService/createcompany/',
            method: 'POST',
            data : Company,
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        alert("Company added successfully.");
                        $scope.getCompanyList();
                        clearUI();
            }).catch(function (e) {
                        $scope.error = e +"Unable to add company.";
        });
    };
   
    //Update Company.
     $scope.updateCompany = function (Company) {
            $http({
            url: 'http://localhost:8080/SpringMavenRestDemoService/updatecompany/',
            method: 'POST',
            data : Company,
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        alert("Company updated successfully.");
                        $scope.getCompanyList();
                        clearUI();
            }).catch(function (e) {
                        $scope.error = e +"Unable to update company.";
        });
        };
   
    //Delete Company.
    $scope.deletecompany = function (Company) {     
   
       $http({
            url: 'http://localhost:8080/SpringMavenRestDemoService/deletecompany/'+ Company.companyId,
            method: 'GET',
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            dataType : "JSONP",
            }).then(function (data) {
                        alert("Company deleted successfully.");
                        $scope.getCompanyList();
                        clearUI();
            }).catch(function (e) {
                        $scope.error = e +"Unable to delete company.";
        });
    };
     
    function clearUI() {
        $scope.Company.companyId = "";
        $scope.Company.name = "";
        $scope.Company.ceo = "";
        $scope.Company.country = "";
        $scope.Company.foundationYear = "";
        $scope.Company.noOfEmployee = "";
    };
 
}]);

Hope this will helpful for someone.

MappingJacksonJsonView not working with Spring 4.x.x

You can see this error line with spring 4.x.x. as:-

Cannot find class [org.springframework.web.servlet.view.json.MappingJacksonJsonView] with Spring 4.2.5.

You may get this error with any version of spring with 4.x.During upgrade of my spring application this issue wasted enough time of mine.Below is bit stack trace of this one issue:-

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping’: Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.web.servlet.view.json.MappingJacksonJsonView] for bean with name ‘xyz’ defined in ServletContext resource [/WEB-INF/xyz-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.web.servlet.view.json.MappingJacksonJsonView…………..

When I verified this issue with some other 4.x release than also this issue was there.The reason of this issue is that “MappingJacksonJsonView” class is deprecated

http://static.javadoc.io/org.springframework/spring-webmvc/4.0.1.RELEASE/deprecated-list.html

and as I was having the version 2.x in my POM for Jackson so above error was coming.

For resolving this issue you will be require to use MappingJackson2JsonView with Jackson 2.x.

I am using my POM entry for Jackson as :-

       <dependency>
    		<groupId>com.fasterxml.jackson.core</groupId>
	    	<artifactId>jackson-databind</artifactId>
    		<version>2.6.5</version>
	</dependency>

and servlet entry for bean as:-

	<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
		<property name="contentType" value="application/json"/>
	</bean>

And now it’s working perfectly.

Hope this will help some one.

Upgrading/Changing Dynamic Web Module Version in Maven Spring Application.

For this purpose I am just referencing the same sample application which we created in my last post i.e. “CREATING RESTFUL WEB SERVICES IN JAVA USING SPRING 4.2.5”.We will upgrade it’s Dynamic Web Module to 3.0,which is currently 2.3.

1)If you will try to change it to 3.0 then you will get a message like:-
“Cannot change version of project facet Dynamic Web Module to 3.0”.

2016March16_1

2)Uncheck this with version i.e. 3.0 and click “Apply” and than click “OK”.

3)Again go to same screen i.e. Project Facets version to “3.0” will be already there and now make it checked now.

2016March16_2
Now Click on “OK” and then on “Apply”.You will be see its impact in project and will see that there is a new folder “WebContent”.
2016March16_3

4)Clean and build your project.Now you will see error as :-
2016March16_4

5)The reason for this is the that we need to change structure of web.xml for 3.0.
So Make your web.xml like below now:-

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xmlns="http://java.sun.com/xml/ns/javaee"
		 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
		 id="WebApp_ID"
		 version="3.0">

	<display-name>Archetype Created Web Application</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/rest-servlet.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>rest</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!--This Servlet mapping will handle all incoming requests -->
	<servlet-mapping>
		<servlet-name>rest</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>
    

Now clean and build your project.Things should be working fine with web module 3.0.

Hope this will help someone.

Creating Restful Web Services In Java Using Spring 4.2.5

First of all just want to mention that I am going to Use Eclipse Kepler Release as IDE for this application.We will be creating this sample application as a base wrapper for an Enterprise application.We will be later on keep extending this sample to a certain level.Let’s also include maven implementation in this sample application.
I hope you will be already aware of Maven.If not just go through the link:-

https://en.wikipedia.org/wiki/Apache_Maven

In this sample application we will creating Restful web services which will just append ‘Hello’ and current date-time to our text which we will be passing by this web service.

Now Here is step by Step implementation of this sample application.

Step1 :-
a)In Eclipse go to File >> New >> Others >> Maven >> Maven Project.Then click Next.
b)Select “maven-archetype-webapp” Under ArtifactId as in below image and press ‘Next’.

2016March14_1
c)Under the group id name  enter ‘com.ssb.webSample’ and Aritfact Id as ‘SpringMavenRestDemoService’.

2016March14_2
d)Click on Finish.

You will be able to ‘SpringMavenRestDemoService’ application in your project list.Now open this application.
Step2:-

Open the ‘pom.xml’ of ‘SpringMavenRestDemoService‘ in text editor. And Replace it’s content with content below:-

<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/maven-v4_0_0.xsd">
  
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ssb.webSample</groupId>
  <artifactId>SpringMavenRestDemoService</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMavenRestDemoService</name>
  <url>http://maven.apache.org</url>
 
 <properties>
		<spring.version>4.2.5.RELEASE</spring.version>
		<jdk.version>1.7</jdk.version>
 </properties>
 
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
	  <groupId>javax.servlet</groupId>
	  <artifactId>javax.servlet-api</artifactId>
	  <version>3.1.0</version>
	</dependency>
	<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
	</dependency>
	<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
	</dependency>
  </dependencies>

  <build>
		<finalName>SpringMavenRestDemoService</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
  
</project>

I am using latest spring version that is 4.2.5.

After this press right mouse click on project. Than Click on “Maven” and Click on “Update Project” and update by clicking on ‘OK’ button.

Step 3:-
Now Lets configure our ‘webapp’ as per below:-

a)web.xml inside ‘WEB-INF’:-

<!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>rest</servlet-name>
		 <servlet-class>
		  org.springframework.web.servlet.DispatcherServlet
		 </servlet-class>
		 <load-on-startup>1</load-on-startup>
	  </servlet>

	<servlet-mapping>
		 <servlet-name>rest</servlet-name>
		 <url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>

b)rest-servlet.xml inside ‘WEB-INF’:-

<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.ssb.webSample.SpringMavenRestDemoService.controllers" />

</beans>

Step 4:-

Now Create a class with name ‘ServiceController’ under package “com.ssb.webSample.SpringMavenRestDemoService.controllers” inside a folder ‘java’.

2016March14_3

Below is code for that:-
package com.ssb.webSample.SpringMavenRestDemoService.controllers;

import java.util.Date;

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

@RestController
@RequestMapping(&quot;/sayhello&quot;)
public class ServiceController {

 @RequestMapping(value = &quot;/{userName}&quot;, method = RequestMethod.GET)
 public String sayhello(@PathVariable String userName) {
  Date date = new Date();
  String strMsg =&quot;Hello &quot;+ userName + &quot; Curret Time is : &quot; + date.toString();
  return strMsg;
 }
}

Now build your application and run it.If all goes well you are ready with your service.
Just paste below url in your browser:-

http://localhost:8080/SpringMavenRestDemoService/sayhello/Robert

you can enter any name instead of ‘Robert’.

You Should be able to see the desired output.

 

Hope this will help someone.

 

Unable to publish on server Maven Spring project In Eclipse

With eclipse IDE if you are working with Maven project,you may get this type of exception:-

“Could not publish to the server.java.lang.IndexOutOfBoundsException

When was building my project in eclipse IDE and was trying to publish it to the sever was getting the above mentioned error message and was not able to run the application on server.

After trying multiple steps I was not to fix it.

For resolving this you will require to delete the Maven repository from your machine.

i.e. the .m2 folder which contains all dependencies required for a maven build.

And after that if you will build project from work-space dependencies will be reloaded again and you will able to publish it.

 

Hope this will help someone.