Home arrow Java arrow Page 2 - Adding a Search Service to a Java Application
JAVA

Adding a Search Service to a Java Application


The ability to search a website can be invaluable to visitors. Even if you have a website that searches a product database, your visitors might want to search the contents of your entire site. This article helps you set up such a service. It is excerpted from chapter 10 of the book Better, Faster, Lighter Java, written by Bruce A. Tate and Justin Gehtland (O'Reilly; ISBN: 0596006764).

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 4
November 16, 2006
TABLE OF CONTENTS:
  1. · Adding a Search Service to a Java Application
  2. · Extending jPetStore
  3. · Implementing the Interface
  4. · Registering Our New Class with jPetStore

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Adding a Search Service to a Java Application - Extending jPetStore
(Page 2 of 4 )

We have decided that an existing service layer of the application is unsuited to our current needs. Additionally, we have decided that replacing the service with a new one is the appropriate solution. This situation is a perfect test of extension: how easy will it be to replace this service? Will it involve new code? Changes to existing code? Or just changes to our configuration services?

In order to replace the existing functionality with the Simple Spider, we need to change the output formatting a little (our returns will display full URLs instead of product instances), write a new controller that knows to launch the Simple Spider instead of theProductsDaoobject, and change our mapping layer to point to the new controller. Finally, we’ll use Spider’s configuration service so Spider works better with the new web site.

Looking at these requirements, we can already see we’ll need to write fewer than 100 lines of code and make only minor configuration changes in order to get this to work. It’s a reasonable price to pay for the end result we want. BecausejPetStoreand the Simple Spider were designed to allow for extension in the first place, they fit together well with minimal work.

Conversely, we could write much less code and in fact do almost no work at all if we chose to connect to the Spider through the existing web service interface rather than integrating it directly with thejPetStore. Since the web service interface already exists, it might be construed as a violation of the “do one thing, and do it well” principle to add another, seemingly useless interface. In this instance, though, the added cost of sending a bloated message (XML/SOAP) over a slow transport mechanism (HTTP) is too heavy, especially given the minimal amount of work it will take to get a faster, more efficient integration.

Replacing the Controller

First, let’s replace the SearchProductsController. Here’s the main method of that class:

  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse
           response) throws Exception {
    
if (request.getParameter("search") != null){
         String keyword = request.getParameter("keyword");
         if (keyword == null || keyword.length() == 0) {
             return new ModelAndView("Error", "message",
             "Please enter a keyword to search for,
             then press the search button.");
        
}
         else {
             PagedListHolder productList = new PagedListHolder(
            this.petStore.searchProductList(keyword.toLowerCase()));
    productList.setPageSize(4);
           
request.getSession().setAttribute(
    "SearchProductsController_productList", productList);
    return new ModelAndView("SearchProducts", "productList",
           
productList);
        
}
      }
      else { 
         
String page = request.getParameter("page");
         PagedListHolder productList = (PagedListHolder)
            request.getSession().getAttribute("SearchProductsController_productList");

         if ("next".equals(page)) {
            
productList.nextPage();
         }
         else if ("previous".equals(page)) {
             productList.previousPage();
         }
         return new ModelAndView("SearchProducts", "productList", productList);
      }
   }

The method returns a new instance ofModelAndViewand Spring uses it to determine which JSP to load and how to wire data up to it. The method takes anHttpServletRequestandHttpServletResponse in order to interact directly with the HTTP messages.

The first thing the method does is make sure the user entered a search term. If not, it displays an error to the user; if so, it creates aPagedListHolder calledproductListwith a maximum page size (number of rows per page) set to four. Finally, it calls thepetStoreinstance’ssearchProductList method, which calls toProductsDaoand finally returns theHashMapofProduct instances. The second clause is for when the user clicks the Next Page or Previous Page buttons on the paged list.

Rewrite or Replace?

The next question a conscientious programmer should ask is, does it make more sense to rewrite this class to make use of the Spider, or to write an entirely new
controller? In order to answer that question, we need to consider three more-specific questions first:

  1. Do we have access to the original source? Now that we have thejPetStore application, do we control the source, or is it all binary? If we don’t control the source, we can short-circuit the rest of the decision. We can only replace the class; we can’t rewrite it.
  2. Will we ever need to use the original service again? Assuming we have the source and can rewrite the class, can we foresee ever needing to revert to or make use of the database-search functionality? For the sake of flexibility, we usually want to retain old functionality unchanged, which means we want to replace, not rewrite. However…
  3. Does the current class implement an easily reused interface? If we are going to replace the class, how much work will we have to do to get the application to recognize and accept your new class? Think of this as an organ transplant; how much work and medication has to go into the host body to keep it from rejecting the new organ? Will our changes be localized around the new class or more systemic?

Here’s the answer to these questions: yes, we have the source code; yes, we’ll want access to retain the potential for using the old service; and yes, the controller implements a very simple interface. The controller only needs to implement a single method,handleRequest, which takes anHttpServletRequestand aHttpServletResponseand returns aModelAndView. This means thejPetStoreapplication doesn’t need any systemic changes in order to use our new controller, as long as we support that interface.


blog comments powered by Disqus
JAVA ARTICLES

- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...
- Generics and Limitations in Java
- Getting Started with Java Web Development in...

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials