Adding a New Service

If you want to provide a form where users of web application can send contact requests, this is a simple request that contains sender and message fields. To accomplish this, you must develop a service that can store and read such a contact request.

Prerequisites

This example requires a prepared extension to be set up in a certain way. For details, see Preparing an Extension for ServiceLayer Examples. If you have completed other procedures of the ServiceLayer documentation, you typically have an extension available as needed.

Furthermore this tutorial requires the final extension state of Adding a New Model.

Defining a Model

Defining an Interface for the Service

The service needs a method to find ContactRequest items by sender. Creation and modification of ContactRequest items are done directly at the controller class. While technically it is not necessary to back a service with an interface definition, we recommend using interface-driven design. For more information, see Spring Framework in SAP Commerce.

The interface is placed at the src folder of the extension with the package org.training and looks like this:

org.training.ContactRequestService

package org.training;

public interface ContactRequestService
{
   ContactRequestModel getContactRequest(String sender);
}

Implementing the Service

  1. Implement the service by writing a class implementing the defined interface:

    org.training.impl.DefaultContactRequestService

    package org.training.impl;
    
    public class DefaultContactRequestService implements ContactRequestService
    {
       private FlexibleSearchService flexibleSearchService;
    
       public ContactRequestModel getContactRequest(final String sender)
       {
          final String queryString = "SELECT {PK} FROM {ContactRequest} WHERE {sender} = ?sender";
          final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString);
          query.addQueryParameter("sender", sender);
          final SearchResult<ContactRequestModel> result = this.flexibleSearchService.search(query);
          final int resultCount = result.getTotalCount();
          if (resultCount == 0)
          {
             throw new UnknownIdentifierException(
                "ContactRequest with sender '" + sender + "' not found!"
             );
          }
          else if (resultCount > 1)
          {
             throw new AmbiguousIdentifierException(
                "ContactRequest with sender '" + sender + "' is not unique, " + resultCount
                   + " requests found!"
             );
          }
          return result.getResult().get(0);
       }
    
       public void setFlexibleSearchService(final FlexibleSearchService flexibleSearchService)
       {
          this.flexibleSearchService = flexibleSearchService;
       }
    }
  2. You can now register this service in the Spring configuration to inject it at the controller later. Add the following lines to the training-spring.xml file:

    training/resources/training-spring.xml

    <bean id="contactRequestService" 
       class="org.training.impl.DefaultContactRequestService"  >
       <property name="flexibleSearchService" ref="flexibleSearchService"/>
    </bean>

Creating a Frontend Controller and a View

Create a single view to display, create, and modify ContactRequest s. The view can be called with a sender parameter to display a single ContactRequest of a specific sender. Furthermore it has a form to modify the values of a ContactRequest. If no sender is specified as request parameter, the fields of the form is used to create a new ContactRequest.

  1. Write a frontend controller org.training.web.controllers.ContactRequestController.java. It uses the new ContactRequestService to gather existing ContactRequest s and the ModelService to save or create a ContactRequestModel:

    ContactRequestController

    public class ContactRequestController implements Controller
    {
       private ContactRequestService contactRequestService;
       private ModelService modelService;
    
       @Override
       public ModelAndView handleRequest
          (final HttpServletRequest request, final HttpServletResponse response) throws Exception
       {
          final String sender = request.getParameter("sender");
          ContactRequestModel contactRequest = null;
          if (sender != null)
          {
             try
             {
                contactRequest = contactRequestService.getContactRequest(sender);
             }
             catch (final UnknownIdentifierException e)
             {
                // OK, nothing found
             }
          }
    
          if (request.getMethod().equalsIgnoreCase("POST"))
          {
             if (contactRequest == null)
             {
                contactRequest = new ContactRequestModel();
                modelService.attach(contactRequest);
             }
             final String newSender = request.getParameter("newSender");
             final String newMessage = request.getParameter("newMessage");
             if (newSender != null)
             {
                contactRequest.setSender(newSender);
             }
             if (newMessage != null)
             {
                contactRequest.setMessage(newMessage);
             }
             modelService.save(contactRequest);
          }
    
          final Map<String, Object> model = new HashMap<String, Object>();
          model.put("contactRequest", contactRequest);
          return new ModelAndView("contactRequest.jsp", model);
       }
    
       public void setContactRequestService(final ContactRequestService contactRequestService)
       {
          this.contactRequestService = contactRequestService;
       }
    
       public void setModelService(final ModelService modelService)
       {
          this.modelService = modelService;
       }
    }
  2. Register the controller in the Spring configuration file, such as:

    training/web/webroot/WEB-INF/springmvc-servlet.xml

    <bean name="/contactRequest.html"
       class="org.training.web.controllers.ContactRequestController">
       <property name="contactRequestService" ref="contactRequestService"/>
       <property name="modelService" ref="modelService"/>
    </bean>
  3. Write the view:

    training/web/webroot/contactRequest.jsp

    <html>
    <head><title>Contact Request</title></head>
    <body>
       <form method="post">
           <label for="login">Sender: </label>
           <input type="text" name="newSender" value="${contactRequest.sender}"/>
           <br/>
           <label for="password">Message:</label>
           <textarea name="newMessage">${contactRequest.message}</textarea>
           <br/>
           <input type="submit" value="Send"/>
       </form>
    </body>
    </html>

(Optional) Implementing a Data Access Object (DAO)

The Data Access Object (DAO) pattern allows isolating persistence layer accesses from the business logic. You define an interface that contains all data access methods. Usually, DAOs will have finder methods that run searches on the persistence layer (such as While the service could directly access the persistence layer, it is better to put all storage related logic in a separate class. That way, you can better mock and test, but you can also switch the underlying storage implementation more easily.findByCode(...)) or methods to save, update, and remove objects.

The DAO is the bridge between models and items. SAP Commerce provides base classes that handle the conversion for you but you still have to use the FlexibleSearch to find your objects.

For more information, see:

Generally, you have several options to implement a DAO:

  • You can extend from AbstractItemDaoWhile the service could directly access the persistence layer, it is better to put all storage related logic in a separate class. That, which provides many helper methods and already has injected the ModelService and FlexibleSearchService to facilitate the item retrieval.

  • You can implement the Dao interface (de.hybris.platform.servicelayer.internal.dao package)

    The Dao interface is only a marker and does not declare any methods. By consequence, you will need to declare a sub-interface of Dao for your implementation class, such as:

    public interface MyDao extends Dao
    {
       public void myMethod()
    }

For this example, you are going to define a sub-interface and extend from AbstractItemDao.

  1. The Dao interface does not declare a method to find contact requests by sender, so you need to define a sub-interface:

    org.training.daos.ContactRequestDao

    package org.training.daos;
    
    public interface ContactRequestDao extends Dao
    {
       public List<ContactRequestModel> findBySender(String sender);
    }
  2. For this DAO implementation, extend from AbstractItemDao, such as:

    org.training.daos.impl.DefaultContactRequestDao

    package org.training.daos.impl;
    
    public class DefaultContactRequestDao extends AbstractItemDao implements ContactRequestDao
    {
    
       public List<ContactRequestModel> findBySender(final String sender)
       {
          final String queryString = String.format("SELECT {%s} FROM {%s} WHERE {%s} = ?sender", 
                ContactRequest.PK, "ContactRequest",
                ContactRequest.SENDER);
          final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString);
          query.addQueryParameter("sender", sender);
          final SearchResult<ContactRequestModel> result = flexibleSearchService.search(query);
          return result.getResult();
       }
    
    }
  3. Now you have to create a bean definition for this DAO:

    training/resources/training-spring.xml

    <bean id="contactRequestDao" 
       class="org.training.daos.impl.DefaultContactRequestDao" 
       parent="abstractItemDao"  />

    This bean definition references abstractItemDao as parent. Thus, make sure you have the flexibleSearchService properly injected.

  4. You can now adjust the service you already implemented to use the DAO instead of using the FlexibleSearch directly:

    org.training.impl.DefaultContactRequestService

    package org.training.impl;
    
    public class DefaultContactRequestService implements ContactRequestService
    {
    
       private ContactRequestDao contactRequestDao;
    
       public ContactRequestModel getContactRequest(final String sender)
       {
          final List<ContactRequestModel> result = contactRequestDao.findBySender(sender);
          final int resultCount = result.size();
          if (resultCount == 0)
          {
             throw new UnknownIdentifierException(
                "ContactRequest with sender '" + sender + "' not found!"
             );
          }
          else if (resultCount > 1)
          {
             throw new AmbiguousIdentifierException(
                "ContactRequest with sender '" + sender + "' is not unique, "
                   + resultCount + " requests found!"
             );
          }
          return result.iterator().next();
       }
    
       public void setContactRequestDao(final ContactRequestDao contactRequestDao)
       {
          this.contactRequestDao = contactRequestDao;
       }
    }
  5. Modify the bean definition of the service, such as:

    training/resources/training-spring.xml

    <bean id="contactRequestService"
       class="org.training.impl.DefaultContactRequestService"  >
       <property name="contactRequestDao" ref="contactRequestDao"/>
    </bean>

Other ServiceLayer Procedures