Sunday, May 10, 2009

Easy remoting with Spring HttpInvoker

If you’re looking for a simple solution to expose/access services using Java, maybe you should consider using SpringHttpInvoker. Here’s a quick recipe of how to use it (extracted from Spring docs).

Let’s start with the domain class:

public class Account implements Serializable{
private String name;
public String getName(){
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

The service interface:

public interface AccountService {
public void insertAccount(Account account);
public List getAccounts(String name);
}


And some implementation of the service:

// the implementation doing nothing at the moment
public class AccountServiceImpl implements AccountService {
public void insertAccount(Account acc) {
// do something...
}
public List getAccounts(String name) {
// do something...
}
}



In order to expose this service you’ll need a ServletDispatcher configured inside your web.xml like the following:

<servlet>
<servlet-name>remoting</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>remoting</servlet-name>
<url-pattern>/remoting/*</url-pattern>
</servlet-mapping>


And then it’s just a matter of exposing your service in the WEB-INF/remoting-servlet.xml file:

<bean name="/AccountService"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="accountService">
<property name="serviceInterface" value="example.AccountService">
</bean>


And that’s all you need! To access it on the client application, you just need to declare the remote service:

<bean id="httpAccountServiceProxy"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl"
value="http://remotehost:8080/remoting/AccountService"/>
<property name="serviceInterface" value="example.AccountService">
</bean>



After this point your client application can use your service transparently via the httpAccountServiceProxy. As simple as it should be!

No comments: