10.5. Testing ZipCodes with the ServiceStart the hosted application from Eclipse, using the Run Debug menu command. The GWT development shell should start up, along with a browser window that displays the ZipCodes client. Enter a zip code in the zip code field and press Tab. Figure 10-12 shows the result. Figure 10-12. ZipCodes application with a serviceWe've got a clientbut we don't have a backend service, so all we have is bogus data. (Remember that ResponseServiceImpl in Example 10-8 returns the hardcoded values "state" and "city".) All we need now is a way to look up the state and city information in the database, just like we've done in previous chapters. Adding the DatabaseConnector class, the ZipcodeManager class, and the POJO Zipcode class should do the trick. Those classes were described earlier in this book, but the source code is provided here for reference. The DatabaseConnector class is reproduced in Example 10-11. Example 10-11. DatabaseConnector.java
Example 10-12 presents the code for the ZipcodeManager class. Example 10-12. ZipcodeManager.java
Finally, the Zipcode class is presented in Example 10-13. Example 10-13. Zipcode.java
Figure 10-13 shows what the project looks like after these classes have been added to the server package. Figure 10-13. The complete and final ZipCodes projectNow connect the ZipcodeManager to the displayResponse( ) method of the ResponseServiceImpl class. The ZipcodeManager.getZipcode( ) method returns a POJO Zipcode that contains the city and state corresponding to the zip code: public String displayResponse(String req) { if (req.length( ) < 1) { throw new IllegalArgumentException( "Blank submissions from the client are invalid."); } Zipcode zipcode = ZipcodeManager.getZipcode(req); String state = zipcode.getState( ); String city = zipcode.getCity( ); if ((state==null || state.length()<1) || (city==null || city.length( )<1)) return null; String jsonString = "{\"state\":\""+state+"\", \"city\":\""+city+"\"}"; return jsonString; } In order for the application to connect to the database, the MySQL connector must be in the classpath. If you haven't done it already, download the connector from http://www.mysql.org and add the .jar file to the Classpath tab of Eclipse's Debug window (Run Debug). That completes the plumbing for the ZipCodes application. Now it should be fully functional; Figure 10-14 shows the result. Try setting breakpoints in the client and in the service to verify that you can fully debug the application. It almost seems too good to be true! Figure 10-14. Final client for the ZipCodes applicationWell, you made it! You should now be familiar with all the basics for building an Ajax application with the Google Web Toolkit. For more examples, refer to the GWT home page at http://code.google.com. |