Create a new HTML file in the war directory of your application. In that directory, you will find an index.html that is generated for you. So you can either use index.html or generate a new HTML file as I have done. Name this file as dictionary.html and code it as shown below:
The first thing that we will do is to code out a simple HTML form that takes a single parameter as an input. This parameter is the word that we need to lookup in the
dictionary. We will use a bit of AJAX here to dynamically call our servlet and display the response that we get.
<html> <head> <scripttype="text/javascript"> var xmlhttp; function lookupDictionary(word) { xmlhttp=null; if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc. xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
if (xmlhttp!=null) {
xmlhttp.onreadystatechange=state_Change;
var url = "/gaejdictionaryservice?word="+word; xmlhttp.open("GET",url,true);
xmlhttp.send(null); }
else {
alert("Your browser does not support XMLHTTP."); } } function state_Change() { if (xmlhttp.readyState==4) {// 4 = "loaded" if (xmlhttp.status==200) { // 200 = "OK" document.getElementById('DictionaryServiceResponse').innerHTML=xmlhttp .responseText; } else {
} } } </script> </head> <body> <h2>Dictionary Lookup </h2> <hr/>
<h3>(Powered by Aonaware <a
href="http://services.aonaware.com/DictService/">Dictionary Service</a>)</h3>
<hr/> <p>
<b>Lookup meaning of word:</b><inputtype="text"id="word"></input> </p> <p><b>Meaning :</b> <br/><spanid="DictionaryServiceResponse"></span> </p> <buttononclick="lookupDictionary(word.value)">Lookup Dictionary</button> </body>
Here are some key points from the code above. For most web programmers it is pretty
1. We have a single input field HTML element with an id named word. There is a
2. object
hich contains the
3. t we will be seeing in
4. se when returned is inserted into the span element named
response
Next we shall code the heart of our application a servlet named much standard stuff:
button with a label Lookup Dictionary, on click on which, we invoke a Javascript function called lookupDictionary, passing in the word value. The lookupDictionary method builds up the standard XMLHttpRequest that we shall use to send our request across. The request url is
/gaejdictionaryservice with a single parameter named word, w value of the word that we need to lookup in the dictionary. Note that /gaejdictionaryservice is our servlet endpoint tha
the next section. This servlet will take it the word parameter, and use the URL Fetch Service to invoke the external Dictionary API and return us back the response.
The respon
DictionaryServiceResponse in the above HTML form to display the received.
GAEJDictionaryService.
Coding the GAEJDictionaryService Servlet
[GAEJDictionaryService.java]
Episode 4:Building a Dictionary App:Using the GAEJ URL Fetch Service 40
Create a new Servlet in your Project as shown below. I have created the
GAEJDictionaryService.java in the package com.gaejexperiments.networking. You can choose a package of your choice. The code is straightforward and is listed below:
packagecom.gaejexperiments.networking; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStreamReader; importjava.io.StringReader; importjava.net.URL; importjavax.servlet.ServletException; importjavax.servlet.http.*; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory; importjavax.xml.xpath.XPath; importjavax.xml.xpath.XPathConstants; importjavax.xml.xpath.XPathExpression; importjavax.xml.xpath.XPathFactory; importorg.w3c.dom.Document; importorg.w3c.dom.NodeList; importorg.xml.sax.InputSource; @SuppressWarnings("serial")
publicclassGAEJDictionaryService extendsHttpServlet {
publicvoiddoGet(HttpServletRequest req, HttpServletResponse resp) throwsIOException {
String strCallResult = "";
resp.setContentType("text/plain"); try{
//Extract out the word that needs to be looked up in the Dictionary Service
String strWord = req.getParameter("word");
//Do validations here. Only basic ones i.e. cannot be null/empty
if(strWord == null) thrownewException("Word field cannot be empty.");
//Trim the stuff
strWord = strWord.trim();
if(strWord.length() == 0) thrownewException("Word field cannot be empty."); String strDictionaryServiceCall = "http://services.aonaware.com/DictService/DictService.asmx/Define?word= "; strDictionaryServiceCall += strWord;
URL url = newURL(strDictionaryServiceCall); BufferedReader reader = newBufferedReader(new InputStreamReader(url.openStream()));
StringBuffer response = newStringBuffer(); String line;
while((line = reader.readLine()) != null) { response.append(line); } reader.close(); strCallResult = response.toString(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(newInputSource(new
StringReader(strCallResult.toString())));
XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath();
XPathExpression expr =
xpath.compile("//Definition[Dictionary[Id='wn']]/WordDefinition/text()" );
Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result;
for(inti = 0; i < nodes.getLength(); i++) { strCallResult = nodes.item(i).getNodeValue(); } resp.getWriter().println(strCallResult); }
catch(Exception ex) {
strCallResult = "Fail: "+ ex.getMessage(); resp.getWriter().println(strCallResult); }
}
@Override
publicvoiddoPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {
doGet(req, resp); }
}
Let us go over the key points in the code above:
1. I have provided both GET and POST handlers in the servlet and the POST
handler simply invokes the GET handler here.
2. Then we parse the request parameters for the word parameter that we need to look up in the dictionary (word) and we do some basic validation to make sure that it is not empty.
Episode 4:Building a Dictionary App:Using the GAEJ URL Fetch Service 42
http://services.aonaware.com/DictService/DictService.asmx/Define? word=[YOUR_WORD_HERE]
4. In the above URL, you need to provide the word. So what we do in the code is to simply append the word request parameter that was passed.
5. Next, we use the URL Fetch Service as discussed earlier to collect the entire response.
6. The response returned to use is in XML format and the service returns us the meaning of the word based on 6 dictionaries. We will be using just one of those dictionaries WordNet 2.0 which is the 3rd definition in the XML. I suggest that you punch in the following url to understand what we will be parsing out here. I have used the word ‘engine’ here.
http://services.aonaware.com/DictService/DictService.asmx/Define? word=engine
7. Finally we use XPath. I intentionally used this to demonstrate how easy it is to use XPath to extract out the element text that we are interested in. You are free to choose an alternative way of extracting out the text value. You could use standard SAX/DOM parsing too if you wish. Whatever you are comfortable with will suffice for the example.
8. We first build the Document object by using the standard DocumentBuilderFactory and DocumentBuilder classes.
9. Then on the Document object doc, we evaluate the XPath expression. The XPath expression is //Definition[Dictionary[Id='wn']]/WordDefinition/text().
10.The XPath expression given above can be read as following. First consider the //Definition[DictionaryId ='wn']] which means that find all definitions anywhere in the document which have a child element named DictionaryId whose value is ‘wn’. This is the Definition that we are interested in extracting.
11.Once that is found, comes the rest of the XPath expression, which says that for that Definition element found, get a child element named WordDefinition and extract out its text() value. This is returned as a collection of Text nodes.
12.Finally, we iterate through the Text Nodes and get the value which we then send back as a response.
13.I suggest that if you are still having a problem following the code, try out the URL as mentioned in step 6, study the XML and then the XPath expression will become clear. The rest of the code is standard XML/XPath code from the Java SDK.