Tuesday, 30 September 2014

Spring 3 Rest Web Service Batch Update with JQuery & Ajax Integration

                     Spring 3  Rest Web Service Batch Update with JQuery & Ajax Integration

Hi
    In this blog I will describe the service level changes for Spring batch update.

I am providing the the details of the batch update using jdbcTemplate. Mainly I am using jdbcTemplate.batchUpdate() method to perform the batch update into mysql database.

I am using BatchPreparedStementSetter to implement the batch update in spring restful webservices.

Two methods are uses for batchupdate i.e. 'BatchPreparedStatementSetter' & 'batchUpdate' . The BatchPreparedStatementSetter' is passed as second argument in 'batchUpdate' method. 

The 'getBatchSize' method is used to find the size of the batch. This method is necessary because without it you can't execute 'BatchPreparedStatementSetter' method. 

The 'setValues' method is used here to set the values in place of  '?'. This method is invoked number of times the value returned by  'getBatchSize'  method.

AreaDao :

    Here i am defining the interface (AreaDao) with insertArea() method.

public interface AreaDao {
 public void insertArea(List areas);

}

AreaDaoImpl :

Here I am defining the AreaDaoImpl class and implement the insertArea() method using BatchPreparedStatementSetter.

public void insertArea(final List areas) {
  jdbcTemplate.batchUpdate("INSERT INTO tbl_area " +
    "(area_id, area_location, area_land_mark,email) VALUES (?, ?, ?,?)", new BatchPreparedStatementSetter() {

   public void setValues(PreparedStatement ps, int i)
     throws SQLException {
    Area area = areas.get(i);
    ps.setLong(1, area.getAreaId());
    ps.setString(2, area.getAreaLocation());
    ps.setString(3, area.getAreaLandMark());
    ps.setString(4, area.getEmail());
   }

   public int getBatchSize() {
    return areas.size();
   }

  });

Area :

This is the Area class that represents the Area in the MySql database. The fields are mapping directly to the database table.

public class Area {

private int areaId;
private String areaLocation;
private String areaLandMark;
private String email;

public int getAreaId() {
return areaId;
}
public void setAreaId(int areaId) {
this.areaId = areaId;
}
public String getAreaLocation() {
return areaLocation;
}
public void setAreaLocation(String areaLocation) {
this.areaLocation = areaLocation;
}
public String getAreaLandMark() {
return areaLandMark;
}
public void setAreaLandMark(String areaLandMark) {
this.areaLandMark = areaLandMark;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

AreaService :

Here i am defining the interface (AreaService) with insertArea() method.

public interface AreaService {
 public void insertArea(List areas);

}

AreaServiceImpl :

Here I am defining the AreaServiceImpl class and implement the addArea() method.

public interface AreaServiceImpl implements AreaService  {

@Autowired
private AreaDaoImpl  areaDao;

 public void insertArea(List areas){

           areaDao.insertArea(List areas);


         }

}

AreaController :

DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

Here I am using AreaController to delegate all the AJAX Call from JSP to AreaService.

@Controller
@RequestMapping(value = "/areabatch")
public class AreaController {

    @Autowired
    private AreaServiceImpl  AreaService;

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public void insertArea(@RequestBody List areas) {
        AreaService.insertArea(List areas);

    }


}

I am calling this Rest Full Web Service from JSP using JQuery and Ajax call. This will do the Batch Update for Area in MySql database.



Spring 3 Rest Web Service Batch Update with JQuery & Ajax Integration

                 Spring 3  Rest Web Service Batch Update with JQuery & Ajax Integration

In this blog we will see how to configure the restful web services.

DATABASE :

Here I am creating tbl_area table in MySQL area database.

CREATE TABLE tbl_area(
   AREA_ID   INT NOT NULL AUTO_INCREMENT,
   AREA_LOCATION VARCHAR(20) NOT NULL,
   AREA_LAND_MARK  VARCHAR(20) NOT NULL,
   EMAIL  VARCHAR(20) NOT NULL,
   PRIMARY KEY (AREA_ID)

);

Spring Context Configuration :

Spring Context file Contain all the configuration and initialization for Spring MVC Application.
We need to enable the annotation driven configuration.The base package we need to scan is com.satya.

<mvc:annotation-driven>

<context:component-scan base-package="com.satya">

Spring-Context.xml

cntext2

The ApplicationContext is a subclass of the BeanFactory interface so it has all the functionality a BeanFactory has and more. 

BeanFactory is recommended for lightweight framework like — Mobile and Applet.

1. BeanFactory is core component of Spring IoC container.

2. As ApplicationContext extends BeanFactory so ApplicationContext is more powerful than BeanFactory (like AOP, Internationalization etc.)

You can configure your beans in the Spring IoC container through XML files, properties files, annotations, or even APIs.
1. Container reads these beans by using BeanFactory (or ApplicationContext)
2. Suppose define the beans in XML file, say applicationcontext.xml.
3. Now BeanFactory has to read applicationcontext.xml to load the beans in container.
4. For this BeanFactory needs an interface that can provide the xml file to BeanFactory.
5. This interface called resource object.

<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.1.xsd

        http://www.springframework.org/schema/context 

        http://www.springframework.org/schema/context/spring-context-3.1.xsd

        http://www.springframework.org/schema/mvc

        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
  <mvc:annotation-driven />
  <context:component-scan base-package="com.satya" />

    <!-- Initialization for data source -->
   <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/area"/>
      <property name="username" value="root"/>
      <property name="password" value="root"/>
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id="areaJDBCTemplate" 
      class="com.tutorialspoint.AreaJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

</beans>

We need to create Spring-Beans.xml file to define the ContentNegotiableViewResolver. The CNVR does not resolve the views itself. It delegates to other view resolver.

Spring-Beans.xml :

Here in Spring-Beans.xml file I am using CNVR to resolve views.

<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.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
   
        <bean id="contentNegotiatingViewResolver"
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
                <entry key="request" value="text/html" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                </bean>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <constructor-arg>
                        <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                            <property name="classesToBeBound">
                                <list>
                                    <value>com.satya.domain.Area</value>
                                </list>
                            </property>
                        </bean>
                    </constructor-arg>
                </bean>
            </list>
        </property>
    </bean>  
</beans>

web.xml :

We need to do some modification to the web.xml file depending upon our Spring Restful web service. I am adding spring beans to init and context param.

1. init param - Spring-Beans.xml
2. context param - Spring-Context.xml

<servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>
    org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/Spring-Beans.xml
  </param-value>
  </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.request</url-pattern>
  <url-pattern>*.json</url-pattern>
  <url-pattern>*.xml</url-pattern>
</servlet-mapping>

<context-param>
        <param-name>ContextConfigurationLocation</param-name>
       <param-value>Spring-Context.xml</param-value>
</context-param>

ServletContextListener Spring provides an implementation class ContextLoaderListener class can be used as a listener, it will be created automatically find WEB-INF / applicationContext.xrnl file. Therefore, if only one configuration file, and the file named applicationContext.xml, you only need to add the following code to the web.xml file: 

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


Next blog I will provide service implementation.....................................

Sunday, 28 September 2014

Spring 3 Rest Web Service Batch Update with JQuery & Ajax Integration

                      Spring 3  Rest Web Service Batch Update with JQuery & Ajax Integration


Hi  Readers,
      
        I am going to start how to build  Restful Web Service using Spring 3.1 MVC.
We can use the existing Spring MVC request mapping and the help of JAX-RS 2.0 implementation for JSON and XML marshaling/demarshaling.

  I am using here JQuery and Ajax for Spring Batch Update with MySql database.

AJAX :

Ajax stands for asynchronous JavaScript and XML. If you see another term XHR, which is shorthand for XML HTTP request.

The key to AJAX's concept is "asynchronous". This means something happens to the page after it's loaded. 

Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happen within the lifetime of the page, no refresh or redirection is needed.

Caching Ajax :

 The requested content can either be static (remains exactly the same all the time, such as a contact form or a picture) dynamic requests to the same url get different responses.

For static content, we may want the response cached. But for dynamic content, which can change in a second's time, caching AJAX becomes a bug,  It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. 

We can specify in the AjaxSetup in the $.ajax call.

$.ajaxSetup ({
cache: false
});

$.ajax :

jQuery plays its role in that case and thanks to team of jquery that made this job quite easier for developers by allowing using AJAX jQuery methods and addressing compatibility issues along with simplifying AJAX based calls easier.

The jquery $.ajax() method is used to perform an AJAX (asynchronous ) HTTP request.

$.ajax({
              url :
              type :
              datatype :
              data :
               success :
               failure :
});

name: value options are set of pairs that specify jquery AJAX request. All name/value parameters are optional that are described below.

url: URL to which request is sent in string format

jquery ajax async: The default value is set to be true that means performing request asynchronously in jquery ajax.

data: jquery ajax data to be send to server along with request

dataType: defining the jquery ajax data type expected from server as response

dataFilter: As server sends back data. dataFilter function is used to handle the raw data sent from server in advance. Its complete syntax will be dataFilter(data, type).

error: If request is failed in jquery ajax this call back function is used. Complete syntax is error(xhr,status,error). 

jquery ajax success: If AJAX request succeeds, A callback function to run. Complete syntax of jquery ajax success is: success(result,status,xhr)

global: A Boolean with default value as True. Specifies whether global jquery AJAX event handlers to be triggered or not.

jsonp: This overrides the callback function name in a jsonp request.

processData: A Boolean with default value of True. It tells whether to convert data into query string or not sent in request.

jquery ajax timeout: Local timeout for the request in milliseconds.

type: request type (Get or post) default is Get.

username: User name for HTTP authentication access request

password: password for HTTP authentication access request

BatchUpdate :

We required to insert a batch of records into database in one shot. If you call a single insert method for every record, the SQL statement will be compiled repeatedly and causing your system slow to perform.
We can use JdbcTemplate batchUpdate() method to perform the batch insert operations. With this method, the statement is compiled only once and executed multiple times.

getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
 
}
@Override
public int getBatchSize() {
}
  });

Area.js :

  I am creating Area.js  file for Batch update to MySQL database.

function saveArea() {
     
    var areas=[],
    var area1 = new Object();
    var area2=new Object();
    area1.areaId = $("#areaId1").val();
    area1.areaLocation = $("#areaLocation1").val();  
    area1.areaLandMark = $("#areaLandMark1").val();  
    area1.email = $("#email1").val();

    area2.areaId = $("#areaId2").val();
    area2.areaLocation = $("#areaLocation2").val();
    area2.areaLandMark = $("#areaLandMark2").val();
    area2.email = $("#email2").val();

    areas.push(area1, area2);
    $.ajax({
        type : 'POST',
        url : '/${your project context path here}/areabatch',
        dataType : 'json',
        data : JSON.stringify(areas),
        contentType : 'application/json',
        success : function(data) {
            alert('Batch Update Successfull');
        },
        error : function() {
            alert('error');
        }
    });

}


I will continue in my next blog.........................




Spring 3 Rest Web Service Batch Update with JQuery & Ajax Integration

                      Spring 3  Rest Web Service Batch Update with JQuery & Ajax Integration Hi     In this blog I will describe the...