O'Reilly logo

Jakarta Struts Cookbook by Bill Siggelkow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.5. Decoupling Your Application from External Services

Problem

You want to decouple your Struts application from a specific implementation of an external business service.

Solution

Create an interface that provides an API for the business service. Then use a ServiceFactory class like the one shown in Example 10-13 to provide access to the service.

Example 10-13. Service factory

package com.oreilly.strutsckbk.ch10;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServiceFactory {

    private static Log log = LogFactory.getLog(ServiceFactory.class);
    
    public SecurityService createSecurityService( ) {
        SecurityService service = null;
        try {
            service = (SecurityService)
                Class.forName(securityServiceImpl).newInstance( );
        } catch (Exception e) {
            log.error(
               "Unable to create SecurityService for impl:"+
                    securityServiceImpl);
        }
        return service;
    }

    protected void setSecurityServiceImpl(String securityServiceImpl) {
        this.securityServiceImpl = securityServiceImpl;
    }
    private String securityServiceImpl;
}

You can use a Struts PlugIn, like the one shown in Example 10-14, to bind a service implementation to the interface, and store a reference to the service in the servlet context.

Example 10-14. Service factory plug-in

package com.oreilly.strutsckbk.ch10; import javax.servlet.ServletException; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; public class ServiceFactoryPlugin implements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required