WebService

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 Web-Service in Java Using Eclipse

Just writing a basic small simple step by step implementation for creating web-service in Eclipse and creating client for testing web service. For this one must need to have Java EE version of eclipse.

Setup Application:

   First of all Create a dynamic web project I am naming it as ‘WebServiceTest’.

WSStep1

WSStep2

Creating Java Class As Web Service Provider :-

Now Inside ‘src’ folder just create ‘com’ folder and inside ‘com’ create a folder name as per you, I am just creating ‘bss’. This is just for a good practice as per standards.Now inside ‘bss’ folder I am creating a new class with Name ‘MathService’. Inside this class I am creating a method ‘addNumbers()’ which will be adding two number and will return their submission.

So the Overall Structure will look like below image:-

WSStep3

You have created your web service provider class, As you are using Eclipse, so all next steps are just few mouse clicks.

Building,Deploying and Testing:

Right Click on ‘Java Resources’ folder and go to web service as in below image:-

WSStep4

Select class by clicking on ‘Browse’ button for Service implementation as below:-

WSStep5

Drag both sliders under ‘Test Service’ and ‘Test Client’ to top. Here you can see during the drag that what exactly these are representing.Also make ‘Publish the Web service’ Check box true as below:-

WSStep6

And click on ‘Next’

WSStep7

Again Click on ‘Next’. You will be on below screen:-

WSStep8

Click on ‘Start Server’ button.After this carry on to Click ‘Next’ as in below screens:-

WSStep9

WSStep10

Here in above image you will be see this ‘Launch’ button, currently don’t click on this. I will be explain at last that what is purpose of this.

WSStep11

WSStep12

WSStep13

Finally in above screen click on ‘Finish’.After clicking on Finish you will be see what you need. You can see in browser that .jsp file is there for testing your web service, you can test your methods and see expected result as in below images:-

WSStep14

WSStep15

So that’s all here. But don’t forgot to explore each and every class which are created inside ‘WebServiceTest‘ and ‘WebServiceTestClient‘ for actual implementation.

One additional test approach is also there:-

As above at once place there was a button ‘Launch’,by clicking on that also we can test  web service,in that case you can see result as below:-

WsdlTestStep1

WsdlTestStep2

Hope this will help someone.

Enjoy………………

Just want to add an additional information that some times  during this exercise you may find an Exception like this:-

java.lang.Exception: Couldn’t find a matching Java operation for WSDD operation YourMehodName

This is bit confusing….. The only reason for this is that inside your .java class you have written method name starting with capital letter.If in our case we have written method name as AddNumbers() then we will get this error. So for avoiding this simply make first character small in your method name.

Below is full trace of this Exception:-

java.lang.Exception: Couldn’t find a matching Java operation for WSDD operation “addNumbers” (2 args)  at org.apache.axis.InternalException.<init>(InternalException.java:71)  at org.apache.axis.description.JavaServiceDesc.loadServiceDescByIntrospection(JavaServiceDesc.java:902)  at org.apache.axis.providers.java.JavaProvider.initServiceDesc(JavaProvider.java:477)  at org.apache.axis.handlers.soap.SOAPService.getInitializedServiceDesc(SOAPService.java:286)  at org.apache.axis.deployment.wsdd.WSDDService.makeNewInstance(WSDDService.java:500)  at org.apache.axis.deployment.wsdd.WSDDDeployableItem.getNewInstance(WSDDDeployableItem.java:274)  at org.apache.axis.deployment.wsdd.WSDDDeployableItem.getInstance(WSDDDeployableItem.java:260)  at org.apache.axis.deployment.wsdd.WSDDDeployment.getService(WSDDDeployment.java:427)  at org.apache.axis.configuration.FileProvider.getService(FileProvider.java:231)  at org.apache.axis.AxisEngine.getService(AxisEngine.java:311)  at org.apache.axis.MessageContext.setTargetService(MessageContext.java:756)  at org.apache.axis.handlers.http.URLMapper.invoke(URLMapper.java:50)  at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)  at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)  at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)  at org.apache.axis.server.AxisServer.invoke(AxisServer.java:239)  at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)  at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)  at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)  at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)  at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)  at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)  at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)  at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)  at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)  at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)  at java.lang.Thread.run(Unknown Source)

 

 

Keep Coding……….