Archive

Author Archive

Spring @Cacheable and @CacheEvict explained in simple terms

March 23, 2013 8 comments

In Spring 3.1 we have a feature called Caching, It caches the data based on java method execution, if the java method executed before with same parameters it returns the cached data, other wise it will execute the method and puts the data into cache.

To enable caching :


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven />
//your beans
</beans>

<cache:annotation-driven />  Will recognize the spring cache annotations @Cacheable and @CacheEvict

Spring cache provides

@Cacheable annotation and @CacheEvict annotation.

Put @Cacheable on the method which you want to cache.

Ex:


@Cacheable(value="messagecache", key="#id", condition="id < 10")

public String getMessage(int id){

return "hello"+id;

}

Here getMessage() method is marked with @Cacheable, whenever getMessage() is called it will check the messagecache, if the data is already in messagecache it will return that otherwise it will executes the getMessage() and returns data.

@Cacheable annotations has 3 attributes

  1. Value : is the cache name and it is mandatory, in example it is “messagecache”
  2. Key: based on this data will be cached and it is optional
  3. Condition:  based on the condition data will be cached. In example if the id < 10 then only data will be cached otherwise won’t. it is optional

@CacheEvict annotation will be used to delete the data from existing cache.

@CacheEvict(“employees”)

public void saveEmployee(Employee e){

}

Here whenever a saveEmployee() is called cache will be deleted.

@CacheEvict has 5 attributes:

  1. Value, 2 Key, 3 condition are similar to @Cacheable, apart from these 3 we have another 2 attributes
    1. allEntries : is a Boolean type and delete entire cache
    2. beforeInvocation: is Boolean type and will delete the cache before the method execution

Will go through one small example:

In this example I have used ehcache, refer www.ehcache.org for more information

applicationContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Scans within the base package of the application for @Components to configure as beans -->
<context:component-scan base-package="com" />

<!-- Process cache annotations -->
<cache:annotation-driven />

<!-- Configuration for using Ehcache as the cache manager-->
<bean id="cacheManager" p:cache-manager-ref="ehcache"/>
<bean id="ehcache" p:config-location="classpath:ehcache.xml"/>

<bean id="employee" class="com.java2practice.model.Employee"/>

</beans>

ehcache.xml


<ehcache>
<diskStore path="java.io.tmpdir"/>
<cache name="employeeCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>

</ehcache>

Employee pojo:


package com.java2practice.model;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;

public class Employee {

Logger logger = LoggerFactory.getLogger(getClass());

@Cacheable(value="employeeCache", key = "#id")
public String getEmployee(Integer id){
logger.info("get employee called");
return "employee"+id;
}

}

This Employee class is injected into controller:

Controller :


package com.java2practice.web;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.java2practice.model.Employee;
@Controller
public class WebController {

@Autowired
Employee employee;

@RequestMapping("/index.htm")
public String homePage(@RequestParam(required= false) Integer id, HashMap<String, String> map){
map.put("message", employee.getEmployee(id));
return "index";
}
}

And finally here is my JSP code:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cache Example</title>
</head>
<body>
<h1>This is ${message }</h1>
</body>
</html>

First time for the URL : http://localhost:8080/springcache/index.htm?id=1

Employee class getEmployee() method will be executed and data will be placed in cache. second time for the same request with id=1 getEmployee() method wont be executed, this can be seen by using the log message “get employee called” prints only for the first time.

And for the http://localhost:8080/springcache/index.htm?id=2

getEmployee() will be called and data will be placed in cache.

Here id is the Key, if id changes method will be executed and data will be placed in cache with the key.

When ever the requests comes for the @Cacheable annotated method, spring will check the key in corresponding cache if the cache has key in it. data will be returned from the cache other wise method will be executed.

Instead of ehcache we can use Spring SimpleCacheManager also:


<!-- Configuration for using SimpleCacheManager as the cache manager-->
 <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager" >
 <property name="caches">
 <set>
 <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"  p:name="employeeCache"/>
 </set>
 </property>
 </bean>

Advertisements
Categories: Spring

How to use LinkedIn Javascript API

March 14, 2013 13 comments

Before integrating with Linkedin javascript API we need to register our application with Linkedin.

To do this go to  https://www.linkedin.com/secure/developer, in the Javascript domains add your application URL, localhost is accepted

Below code will describes how to add linkedin sign in button to your application.

Sample JSP file:


<!-- 1. Include the LinkedIn JavaScript API and define a onLoad callback function -->

<script type="text/javascript" src="http://platform.linkedin.com/in.js">

api_key: your_api_key

scope: r_network,r_emailaddress,r_fullprofile,r_basicprofile,r_contactinfo

</script>

</head>

<body>

<!-- need to be logged in to use Search; if not, offer a login button -->

<script type="IN/Login"></script>

</body>

That’s it, linkedin sign in button will appear in your page, if you click on it based on the scope it will ask your permissions.

For searching people from your application , we have to use Linkedin People Search API

To use linkedin search API, i have developed small program. It will ask for first name and last name, based on the given data it will search in linked in and prints the result in UI.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>LinkedIn JavaScript API Hello World</title>

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>

<!-- 1. Include the LinkedIn JavaScript API and define a onLoad callback function -->

<script type="text/javascript" src="http://platform.linkedin.com/in.js">

api_key: your_api_key

scope: r_network,r_emailaddress,r_fullprofile,r_basicprofile,r_contactinfo

</script>

<script type="text/javascript">

function searchClick() {

alert($("#firstNameId").val()+":"+$("#lastNameId").val());

if (!IN.ENV.auth.oauth_token) {

alert("You must login w/ LinkedIn to use the Search functionality!");

return;

}

IN.API.PeopleSearch()

.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",

"summary","numConnections")

.params({

"first-name": $("#firstNameId").val(),

"last-name": $("#lastNameId").val(),

"count":25

})

.result(function(result, metadata) {

setSearchResults(result.people.values);

});

}

function setSearchResults(values) {

var table = $("#resulttable");

table.append('<tr><th>First Name</th><th>Last Name</th><th>Head Line</th><th>Industry</th><th>Picture</th><th>No Of Connections</th><th>Summary</th><th>Positions</th></tr>');

for (i in values) {

try{

var person = values[i];

var positionsStr = "<ul>";

for(i in person.positions.values){

positionsStr+="<li>"+person.positions.values[i].company.name+"</li>";

}

console.log(positionsStr);

table.append('<tr><td>'+

person.firstName+'</td><td>'+

person.lastName+'</td><td>'+

person.headline+'</td><td>'+

person.industry+'</td><td><img src="'+

person.pictureUrl+'"/></td><td>'+

person.numConnections+'</td><td>'+

person.summary+'</td><td>'+

positionsStr+'</ul></td></tr>')

}catch(err){alert(err);}

}

}

</script>

</head>

<body>

<!-- need to be logged in to use Search; if not, offer a login button -->

<div align="right">

<script type="IN/Login"></script>

</div>

<center>

<p>Basic test of the People Search API via Connect.</p>

First Name: <input type="text" name="firstName" id="firstNameId"/><br/>

Last Name: <input type="text" name="lastName" id="lastNameId"/><br/>

<input type="button" name="searchLinkedIn" value="Search LinkedIn!" onclick="searchClick();"/>

</center>

<table id="resulttable">

</table>

</body>

</html>

Thats it, for further info regarding Linkedin API http://api.linkedin.com/

Categories: linkedin

How to pass JSON Object string or JSONArray string from javascript to spring controller

March 14, 2013 13 comments

We usually send primitive data to spring controller by using @RequestParam annotation. But how to pass whole JSONObject string or JSONArray string to spring controller directly.

For that we have to include below jar files in buildpath

  1. jackson-core-asl-1.7.3.jar
  2. jackson-mapper-asl-1.7.3.jar

I have created Person pojo which will be mapped with javascript JSONObject exactly, Whatever the identifiers are there in this POJO should be there in Javascript JSON.

public class Person implements Serializable{
private String id;
private String firstName;
private String lastName;
//setters and getters
}

Pojo should implement Serializable interface, as  Jackson will serialize and deserialize to send data between server and client.

Our json data is :
{"persons": [
{
"firstName": "Ramesh",
"id": "id1",
"lastName": "Kotha"
},
{
"firstName": "Sathish",
"id": "id2",
"lastName": "Kotha"
}
]
}

Below is an ajax request from jsp.

$.ajax({
type: 'POST',
dataType: 'json',
contentType:'application/json',
url: "create_persons.htm",
data:JSON.stringify(arr),
success: function(data, textStatus ){
console.log(data);
//alert("success");
},
error: function(xhr, textStatus, errorThrown){
//alert('request failed'+errorThrown);
}
});

Now will see Spring controller Code:

@RequestMapping(value="/create_persons.htm")
public @ResponseBody createPerson(@RequestBody Person[] persons){
//here you can persons array as normal
for(Person person : persons){
System.out.println(person.getId());
}
}

By seeing @RequestBody annontation json data will be converted into Java Person[] and passed to persons array.

Add this in your Configuration file :

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>

That’s it, now if you pass json string to the spring controller, it will be converted into java POJO.

Categories: Java, Spring

How to solve org.apache.lucene.index.CorruptIndexException?

February 19, 2013 Leave a comment

If solr server stops while indexing is going on, we may get org.apache.lucene.index.CorruptIndexException error.

To solve this we have to use org.apache.lucene.index.CheckIndex class. We have to run this class to fix the corrupted indexes in solr.

1.  First take back up your indexed data
2.  Go to the directory where lucene-core.3.6.1.jar is there

3. then run this command
java -cp lucene-core-3.1.0.jar -ea:org.apache.lucene… org.apache.lucene.index.CheckIndex “your indexed directory path” –fix
in my case it is
java -cp lucene-core-3.1.0.jar -ea:org.apache.lucene… org.apache.lucene.index.CheckIndex “C:\Program Files\gisgraphy-3.0-beta2\solr\data\index” –fix

corruptedindex

As there are no corrupted indexes in my case it says “No problems were detected with this index”

If there are any corrupted indexes are there then those will be fixed with this command and solr will be working fine.

Categories: Java, solr

Spring AOP explained in simple terms

February 2, 2013 3 comments

Aspect Oriented Programming:

Developer has to concentrate on business logic, Cross cutting functionalities like Transactions, Logging, Data Access Logic should be taken care by container.

This principle is called AOP.

Until I have used AOP, I didn’t recognize its worth:

1.       Let’s explore the non AOP architecture

package com.java2practice.aop;
import java.math.BigDecimal;

public class Account {
BigDecimal currentAmount = new BigDecimal("5000");

public BigDecimal withdraw(BigDecimal withdrawlAmount){
if(withdrawlAmount.compareTo(currentAmount) < 0 )
     return currentAmount.subtract(withdrawlAmount);
else
     throw new FundsNotSufficientException();
 }
}

Do we have any problem with above withdraw method, if we observe closely?

First we should use logging. Otherwise resolving the errors would be a big problem.

For that we will change the above method accordingly

import java.math.BigDecimal;
import org.apache.log4j.Logger;

public class Account {
Logger logger = Logger.getLogger(Account.class);
BigDecimal currentAmount = new BigDecimal("5000");

public BigDecimal withdraw(BigDecimal withdrawlAmount){
    logger.info("withdraw method started");
    if(withdrawlAmount.compareTo(currentAmount) < 0 ){
       return currentAmount.subtract(withdrawlAmount);
   }
   else{
     throw new FundsNotSufficientException();
    }
    logger.info("withdraw method successfully completed");
  }
}

Second there is no Transaction started, As withdraw method going update the currentAmount in Database it should be within Transaction so will add transaction.

import java.math.BigDecimal;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Account {
Logger logger = Logger.getLogger(Account.class);
BigDecimal currentAmount = new BigDecimal("5000");

public BigDecimal withdraw(BigDecimal withdrawlAmount){
   Transaction tx = null;
   Session session = getCurrentSession();
   try{
     logger.info("withdraw method started");
     if(withdrawlAmount.compareTo(currentAmount) < 0 ){
        tx = session.beginTransaction();
        currentAmount = currentAmount.subtract(withdrawlAmount);
        tx.commit();
        return currentAmount;
       }
     else{
       tx.rollback();
       logger.debug("FundsNotSufficientException :: withdraw method failed");
       throw new FundsNotSufficientException();
    }
   logger.info("withdraw method successfully completed");
 }catch(Exception ex){
   tx.rollback()
   logger.debug("withdraw method failed");
   }
  }
}

Now we implemented Transactions and logging successfully but what we are doing if any new requirement is coming we are changing the BankAccount class which is against Object Oriented principle.

If we think again there should be data access logic for the Bank Account class then we have to change once again the class to like this:

package com.java2practice.aop;
import java.math.BigDecimal;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Account {
Logger logger = Logger.getLogger(Account.class);
BigDecimal currentAmount = new BigDecimal("5000");

public BigDecimal withdraw(BigDecimal withdrawlAmount){
    logger.info("withdraw method started");
    Transaction tx = null;
    Session session = getCurrentSession();
    try{
      if(currentUser.isWIthdrawEnabled()){
        if(withdrawlAmount.compareTo(currentAmount) < 0 ){
          tx = session.beginTransaction();
          currentAmount = currentAmount.subtract(withdrawlAmount);
          tx.commit();
          return currentAmount;
        }
      else{
        tx.rollback();
        logger.debug("FundsNotSufficientException :: withdraw method failed");
        throw new FundsNotSufficientException();
       }
     logger.info("withdraw method successfully completed");
     }else {
     logger.info("withdraw method Failed withdrawal is disabled for this user");
   }
  }catch(Exception ex){
    tx.rollback();
    logger.debug("withdraw method failed");
   }
  }
}

Now it looks fine, but in future any new cross cutting functionality comes, we need to change the Bank Account class once again. What if we separate the cross cutting functionalities like Logging, Security, Transaction to outside of the business logic then we can add new cross cutting functionality without touching BankAccount class.

Imagine if the Data access logic changes, we may need to change lot of files. Same with the entire cross cutting functionalities, They should not be coupled with the business logic and should be defined separately. This we can achieve through Spring AOP.

2. Will see the AOP architecture:

For Cross cutting functionality Logging will see the AOP architecture

  1. CustomerDAO.java
package com.java2practice.dao;

public interface CustomerDAO {
   String addCustomer();
   String addCustomerReturnValue()
   void addCustomerThrowException() throws Exception;
   void addCustomerAround(String name);
}
  1. CustomerDAOImpl.java
package com.java2practice.dao.impl;
import com.java2practice.dao.CustomerDAO;

public class CustomerDAOImpl implements CustomerDAO {
  public String addCustomer(){
     System.out.println("addCustomer() is running ");
     //throw new ArithmeticException();
     return "ramesh";
   }
  public String addCustomerReturnValue(){
     System.out.println("addCustomerReturnValue() is running ");
     return "abc";
  }
  public void addCustomerThrowException() throws Exception {
     System.out.println("addCustomerThrowException() is running ");
     throw new Exception("Generic Error");
   }
  public void addCustomerAround(String name){
    System.out.println("addCustomerAround() is running, args : " + name);
  }
}

Here logging will be implemented by AOP, for that we need to write an Aspect.

  1. LoggingAspect.java
package com.java2practice.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
  @Before("execution(* com.java2practice.dao.*.*(..))")
  public void logBefore(JoinPoint joinPoint) {
     System.out.println(joinPoint.getSignature().getName()+" is started! from logBefore");
  }
  @After("execution(* com.java2practice.dao.*.*(..))")
  public void logAfter(JoinPoint joinPoint){
    System.out.println(joinPoint.getSignature().getName()+" is completed! from logAfter");
  }
  @AfterThrowing(pointcut = "execution(* com.java2practice.dao.CustomerDAO.*(..))", throwing= "error")
  public void logAround(JoinPoint joinPoint, Object error){
    System.out.println(joinPoint.getSignature().getName()+" after throwing called! from after throwing "+error);
  }
  @AfterReturning(  pointcut = "execution(* com.java2practice.dao.CustomerDAO.addCustomerReturnValue(..))", returning= "result")
  public void afterReturning(JoinPoint joinPoint, Object result){
    System.out.println("after returning called result: "+result);
  }
  @Around("execution(* com.java2practice.dao.CustomerDAO.addCustomerAround(..))")
  public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("Around before is running!");
    if(joinPoint.getArgs()[0].equals("ramesh")){
       joinPoint.proceed(); //continue on the intercepted method
       System.out.println("Around after is running!");
     }
    else{
      System.out.println("you dont have permission to call this method");
    }
  }
}
  1. @Aspect annotation will tells the container it is an Aspect
  2. @Before(“execution(* com.java2practice.dao.*.*(..))”) — it will be executed before any method executes  in com.java2.practice.dao package
  3. @After(“execution(* com.java2practice.dao.*.*(..))”) — it will be executed after any method execution in com.java2.practice.dao package
  4. @AfterThrowing(pointcut = “execution(* com.java2practice.dao.CustomerDAO.*(..))”, throwing= “error”) —  It will be executed if any method throws any exception in com.java2practice.dao.CustomerDAO class and the error will be captured in “error”.
  5. @AfterReturning(  pointcut = “execution(* com.java2practice.dao.CustomerDAO.addCustomerReturnValue(..))”, returning= “result”) – it will be executed if com.java2practice.dao.CustomerDAO.addCustomerReturnValue() method returns any value and the returned value will be stored in “result”.
  6. @Around(“execution(* com.java2practice.dao.CustomerDAO.addCustomerAround(..))”) – This is very powerful l aspect, it will be executed before the method execution and after the method execution.  Even we can control the method execution  by joinPoint.proceed()

So now will write spring-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
    <aop:aspectj-autoproxy />
    <bean id="customerDAO" />
    <!-- Aspect -->
    <bean id="logAspect" />
</beans>

Finally will write  Main program to see the power of AOP.

package com.java2practice.aspect;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2practice.dao.CustomerDAO;

public class Main {
  public static void main(String[] args)  {
  ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
  CustomerDAO customer = (CustomerDAO) context.getBean("customerDAO");
  try {
    //customer.addCustomer();
      customer.addCustomerAround("ramesh");
    //customer.addCustomerReturnValue();
    //customer.addCustomerThrowException();
     } catch (Exception e) {
    //e.printStackTrace();
   }
 }
}

Have fun with  AOP.

Categories: Java, Spring

Java Webservice with Axis

WebServices with Apache Axis:

A)     Creating the WebService Server.

  1. Create a java dynamic web project with eclipse    page1
    2.  Create Java Class, this class will contain a method which converts a given string into upper case string, very small method. We will call this method from the webservice client program.

     package com;
    
    public class TestWebService {
    public String getName(String name){
    return name.toUpperCase();
    }
    }
    

3. Righ click on the class select New -> WebServices  -> WebService

page2

4. Click Next -> Next

page3

5. Click on Start Server leave everything as default and click finish

page4

6. Now check http://localhost:8080/WebServiceTest/services/TestWebService?wsdl in browser

It will give you the WSDL file


<wsdl:definitions targetNamespace="http://com"><!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)--><wsdl:types><schema elementFormDefault="qualified" targetNamespace="http://com"><element name="getName"><complexType><sequence><element name="name" type="xsd:string"/></sequence></complexType></element><element name="getNameResponse"><complexType><sequence><element name="getNameReturn" type="xsd:string"/></sequence></complexType></element></schema></wsdl:types><wsdl:message name="getNameRequest"><wsdl:part element="impl:getName" name="parameters">

</wsdl:part></wsdl:message><wsdl:message name="getNameResponse"><wsdl:part element="impl:getNameResponse" name="parameters">

</wsdl:part></wsdl:message><wsdl:portType name="TestWebService"><wsdl:operation name="getName"><wsdl:input message="impl:getNameRequest" name="getNameRequest">

</wsdl:input><wsdl:output message="impl:getNameResponse" name="getNameResponse">

</wsdl:output></wsdl:operation></wsdl:portType><wsdl:binding name="TestWebServiceSoapBinding" type="impl:TestWebService"><wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/><wsdl:operation name="getName"><wsdlsoap:operation soapAction=""/><wsdl:input name="getNameRequest"><wsdlsoap:body use="literal"/></wsdl:input><wsdl:output name="getNameResponse"><wsdlsoap:body use="literal"/></wsdl:output></wsdl:operation></wsdl:binding><wsdl:service name="TestWebServiceService"><wsdl:port binding="impl:TestWebServiceSoapBinding" name="TestWebService"><wsdlsoap:address location="http://localhost:8080/WebServiceTest/services/TestWebService"/></wsdl:port></wsdl:service></wsdl:definitions>

B)     Creating the WebService Client

  1. Right click and select New-> WebService->WebServiceClientpage5
    2. Paste the WSDL path in server definition and change the client project to WebServiceTestClient( you can give anything as a name)
    3. Click Next and Finish
    4. It will create a new java dynamic project with named as WebServiceTestClient and some java files

page6

5. Open TestWebServiceProxy.java and write a main() method in that

TestWebServiceProxy.java

public static void main(String... args){
  try{
    TestWebServiceProxy proxy = new TestWebServiceProxy();
    String name = proxy.getName("webservice");
    System.out.println("name -->"+name);
   }catch(RemoteException re){
     re.printStackTrace();
  }
}

C)     Running the client

Right click on TestWebServiceProxy.java and run as java application, it will print the result in Uppercase.

Categories: Java, WebService

How MVC belongs to only Presentation Layer?

September 16, 2012 4 comments

Spring MVC in simple terms:

It is a presentation framework, you may have doubt “How MVC belongs to only presentation layer”.

MVC Framework:

View and Controller belongs to Presentation Layer as Controller takes the URL and directs to appropriate View based on the given URL.

 MVC Flow:

  1. Request comes to the controller, controller decides is there any business logic to be implemented for this request or not.
  2.  If no business logic required it will redirect to the appropriate View. Ex: if we are requesting a login form no business logic required here so controller directly redirect login.jsp.
  3. If business logic required to the particular request it will call the appropriate Service class to process the request. Based on the service object response, controller redirects to the appropriate view.
  4. In the view if there is any data is to be shown, then the data will be taken from appropriate model.

With the above diagram View and Controller directly interacting with Presentation Layer.

And model is used by View to show the data.

So MVC belongs to Presentation Layer

MVC in Three tier architecture:

In three tier architecture we have Presentation Tier, Middle Tier, Data Access Tier, simply we can call Presentation layer, Service layer  and DAO Layer.

Presentation layer interacts with the Service layer and Service layer interacts with DAO layer.

The Flow will be like this:

  1. Request  comes to controller and controller decides whether this request needs any business logic to be implemented or not
  2. If no it simply returns a view.
  3. If yes it interacts with Service Layer and Service Layer interacts with DAO Layer
  4. Later the based on the response from Service Layer appropriate View will be shown by the Controller.

Spring recommends the same model can be used for presentation layer, In Struts we have form beans as presentation layer model. But in Spring we can use the same model across all the Three Layers.

Categories: Java, Spring