Wednesday, August 24, 2005

Using Ajax in a simple JSF Application - Introduction

I am going to start another tutorial on how to integrate Ajax with JSF soon. This is going to be a very simple JSF application with no GIS component. I hope that this could be of some help to GIS and non-GIS JSF developers alike.
Before I talk about this application, here is a nice article that demonstrates how to create a JSF textbox component with auto-complete feature using Ajax technique:

The above article discusses how to build a custom component that manages the necessary javascript code and can be easily used in a web page. I have, however, used a different approach to create a similar text box. It is simpler in a sense that it doesn't require you to create a custom TextBox component. The downside though is you will have to manage the Javascript code in the jsp page on your own. So if you do not mind writing/using the javascript code yourself, then you might want to give this a try.

The application that I will be discussing will have a text box to enter a country name. As you type a new character in the text box, it will dynamically get upto 5 matching country names from the server and list those names for you to choose from. Once the text box has the selected country name and you submit the form, it will give you a brief description of that country.
To accomplish the Ajax protion of the application, I have used the third strategy discussed in the following article:
If you are a GIS Developer and have gone through my previous discussion on Integrating Ajax with ArcGIS Server, the idea is pretty much the same.

If you would like, you can download this application from here. In order to run this application, simply extract the ajax folder from the zip file, put the JSF jar files in WEB-INF\lib folder and deploy it in a servlet container.

Next time, I will discuss the code behind this application. Stay tuned!!

Tuesday, August 23, 2005

Hidden Input Element

HTML Hidden input element is typically used to transfer hidden data between the client and server. When writing a JSP or ASP application, you might have added a few hidden inputs to your page to persist the data between page reloads. With the evolution of server side technologies like .NET and JSF, the state of a control in the webpage is typically managed in the server side. It is, however, not efficient and sometimes almost impossible to put all data on the server and go back and forth between client and server for every user interaction. Say, for example, in a GIS web application, it would be impossible to post a request to the server to get the map coordinate every time you move the mouse on the map. Hence an efficient web application requires an optimum usage of client side and server side logic which in turn requires transferring the data back and forth between the server and client to make the two sides in synch with each other. The hidden input element can be handy in transferring such data. A typical example of using hidden input elements in a GIS application is passing the updated map extent (minx, miny, maxx, maxy values) between the server and the client.

In my previous blog, I made use of a hidden input element to persist the web page state maintained in the client side. I helped a user with a similar problem using the hidden input element a while ago. This was in .NET. So I thought it would be nice to take a break from Java and talk about it.

The problem was to enable/disable a tool item in the toolbar of the ArcGIS Server MapViewer template on the client side through Javascript without posting back the form immediately. The toolbar is managed by the .NET ADF on the server side. So if you simply change the property on the client side and do not somehow update the change on the server side, you will lose your change the next time your website is loaded. You can, of course, post back the form everytime you enable/disable a toolitem in the client side to synch the server with the client state. However, this means you need to post the form each time you make this change which is not an ideal solution. What would be an ideal solution is to use javascript to enable/disable the toolbar item and when the next time the form is posted, update the state of the toolbar to synch it with the client state.

As mentioned before, we can make use of hidden input control run at the server side to do this. Lets discuss how we can customize the .NET MapViewer template to achieve this functionality:

1. Add a hidden HTML input element to the Default page of the MapViewer template application. Set it to "Run as server Control". Make sure that this is added within the Form element in the HTML source.

2. Add an HTML Button to the page. We will use this button to test our function. Specify onclick="disableToolItem('ZoomOut');" for this button. This button when clicked calls disableToolItem function on the client side and does not post the form.

3. Now lets take a look at disableToolItem function:

function disableToolItem(toolItem){
var f = document.forms[0];
var listValues="";
var Toolbar1 = Toolbars['Toolbar1'];
var items1 = Toolbar1.Items;
disableTool(toolItem, !items1[toolItem].Disabled, true);

listValues += (items1['ZoomIn'].Disabled) ? "0":"1";
listValues += (items1['ZoomOut'].Disabled) ? ":0":":1";
listValues += (items1['Pan'].Disabled) ? ":0":":1";
listValues += (items1['FullExtent'].Disabled) ? ":0":":1";
listValues += (items1['ZoomBack'].Disabled) ? ":0":":1";
listValues += (items1['ZoomNext'].Disabled) ? ":0":":1";
listValues += (items1['Identify'].Disabled) ? ":0":":1";
f.elements['activeToolList'].value = listValues;

Notice that it first toggles the disable property of the given toolItem by calling the custom
function disableTool (see below) and generates a String in
this format: 0:1:1:1:0 where 0 and 1 represent the disabled
and enabled state of the toolitem respectively. It then assigns this value
to the hidden input element and refreshes the toolbar.

4. The disableTool function is given below:

function disableTool(itemName, disable, isTool ){
var Toolbar1 = Toolbars['Toolbar1'];
var items1 = Toolbar1.Items;
items1[itemName].Disabled = disable;
var cellName = 'Toolbar1' + itemName;
var thisCellElement =
thisCellElement.onmousedown == null;
thisCellElement.onmouseover == null;
thisCellElement.onmouseout == null;
} else {
thisCellElement.onmousedown = function () {
if (isTool)
ToolbarMouseDown('Toolbar1', itemName, 'Tool');
ToolbarMouseDown('Toolbar1', itemName, 'Command');

thisCellElement.onmouseover = function () {
ToolbarMouseOver('Toolbar1', itemName);

thisCellElement.onmouseout = function () {
ToolbarMouseOut('Toolbar1', itemName);


This function gets the specified toolbar item and nullifies the
mouse events if disabling. It will activate the mouse events
for toolbar item if enabling.

5. Add the above functions to toolbar_functions.js file in C:\Inetpub\wwwroot\aspnet_client\esri_arcgis_server_webcontrols\9_1\JavaScript folder. (Be sure to keep a back up copy of the original file before you make any change to it.)

6. We need to modify the existing functions as follows:
a) Find ToolbarMouseDown function in toolbar_functions.js file . Inside this function find
this line:

var toolbar = Toolbars[toolbarName];

Add this line after the above line:

if(toolbar.Items[toolbarItemName].Disabled) return;

b) Inside ToolbarMouseOver function, find this line:

var toolbar = Toolbars[toolbarName];

Add this line after the above line:

if(toolbar.Items[toolbarItemName].Disabled) return;

c) Inside ToolbarMouseOut function, find this line:

var toolbar = Toolbars[toolbarName];

Add this line after the above line:

if(toolbar.Items[toolbarItemName].Disabled) return;

7. Finally, we need to update the server state when the page is posted back. Modify the Page_Load method of Default page as shown below:

private void Page_Load(object sender, System.EventArgs e)
// Check parameters of MapControl
// If there is no Host or ServerObject defined,
// then there is no point to continuing since there will be no map to display
if ( (Map1.Host == null) (Map1.Host == String.Empty) )
callErrorPage("Host property not defined for the Map control.", null);
if ( (Map1.ServerObject == null)
(Map1.ServerObject == String.Empty)
(Map1.ServerObject == "(none)") )
callErrorPage("ServerObject property not defined for the Map control.", null);
if (!Map1.AutoFirstDraw)
callErrorPage("The property AutoFirstDraw of
the Map WebControl must be set to true
for this application to run.", null);
// check if the server object can be accessed
ESRI.ArcGIS.Server.WebControls.ServerConnection connection =
if ( connection == null )
callErrorPage("Invalid ServerConnection.", null);

// check if the server object is pooled
isPooled = connection.IsServerObjectPooled(Map1.ServerObject,"MapServer");

string activeTools="";
// Is this a PostBack or just started
if ( !Page.IsPostBack )
// Is this a new session?
if ( Session.IsNewSession )
// Save extent history to Session
m_extenthistory = new ArrayList();
Session.Add("extenthistory", m_extenthistory);
m_lastextent = Map1.Extent;

//if new session, generate the string to store
//the enable/disable status of toomitems
//the value will be stored in 1:0:0:1:1 format
//where 1=enable, 0=disable

int toolLength = Toolbar1.ToolbarItems.Count;
for (int i=0;i<toolLength;i++)
string disableOrNot = "1";
Tool tool = Toolbar1.ToolbarItems[i] as Tool;
if(tool.Disabled) disableOrNot = "0";
if(i==0) activeTools = disableOrNot;
else activeTools = activeTools + ":" + disableOrNot;
} else {
Command command1 = Toolbar1.ToolbarItems[i] as Command;
if(command1.Disabled) disableOrNot = "0";
if(i==0) activeTools = disableOrNot;
else activeTools = activeTools + ":" + disableOrNot;
//set the value to the hidden input control
activeToolList.Value = activeTools;
} else {
//if not a new session
//get the values from the input control
//and update the toolitem property

activeTools = activeToolList.Value;
if((activeTools != "") && (activeTools != null))
char[] sep = {':'};
Array aa = activeTools.Split(sep);
for(int i = 0;i<aa.Length;i++)
Tool tool = Toolbar1.ToolbarItems[i] as Tool;
if(tool != null)
if (aa.GetValue(i).ToString()=="0") tool.Disabled = true;
else tool.Disabled=false;
} else {
Command command1 = Toolbar1.ToolbarItems[i] as Command;
if (aa.GetValue(i).ToString()=="0") command1.Disabled = true;
else command1.Disabled=false;
// make sure that the session is still going, if not, display error page
if (Session["extenthistory"]==null)
callErrorPage("Your session has timed out.", null);

sessionId = Session.SessionID;
string scriptString = "\n<script language=javascript>sessionId = '"
+ sessionId + "'; </script>\n";
Page.RegisterStartupScript("SessionIdScript", scriptString);
// get name of session object holding map description
string pagePath = Page.Request.FilePath;
string pageName = "";
int lastSlash = pagePath.LastIndexOf("/");
if (lastSlash>-1) pageName = pagePath.Substring(lastSlash+1);
m_MapDescriptSessName = pageName + Map1.ID + "_md";

Notice above that when the new session is started, we get the toolitem property and
generate the string to assign it to hidden input control. If this is not a new session but a postback request, we parse the value of hidden input control and update the property of the toolitem appropriately. This makes the state of the server toolbar in synch with that on the client side.

Sunday, August 21, 2005

Integrating AJAX with ArcGIS Server - IV

In this final part of Integrating AJAX with ArcGIS Server series, we will discuss how to customize javascript code for the custom magnifier tool. The most challenging part in this section is to integrate our custom tool in the existing toolbar managed by ArcGIS Server ADF. Java ADF manages the active tool through Map Control in the server side. The magnifier tool that we are developing, however, does not submit the request to ADF but to a separate servlet. So we need to develop our own mechanism to integrate this new tool to the existing toolbar. To solve this problem, we will add a JSF hidden input element to store the state (active or not) of the Magnifier tool and customize the javascript code to update the toolbar in client side. Since JSF components are stored in the server side, we will use this hidden input element to maintain the state of the magnifier tool between the postbacks.
With this introduction, lets discuss the code step by step.

1. We will be writing the javascript code in a separate file called ajax.js. So first thing we will do is add the reference to the js file in the mapviewer.jsp page:

<script language="Javascript" src="js/ajax.js">

(We will take a look at this file in a while.)

2. Add the magnifier tool right after the identify tool in the toolbar:

<IMG id="imgMagnifier"
MapPoint('Map0', 'Magnifier');
onmouseout="ButtonOut('imgMagnifier', 'Map0',
'Magnifier', 'images/magnifier.gif',
'images/magnifierD.gif');" />
<jsfh:inputHidden id="btnMagnifierHidden" value="" />

The above code is similar to other tools except these 2 important differences:
a) In onmousedown event, we have called MapPoint function and passed our custom tool id called Magnifier. Since this is not the ADF managed tool but our own tool, we need to manage it through our custom javascript code.
We will discuss the javascript code just in a bit.
b) As mentioned before, we have added a jsf hidden input component to manage the status of the magnifier tool.

3. Save the following images in images folder of the web application as magnifier.gif, magnifierU.gif and magnifierD.gif respectively:

4. Find the identifyResult control tag and add the following code right after it:

<div id="magnifierDiv"
<div id="mainImg">
<IMG id="magnifierDivImg" src="" />
<div id="closeImg"
style="position:absolute;left:180px; top:5px;">
<IMG id="magnifierCloseImg"
onmousedown="closeMagnifier();" />

In the above code, we have added a div element with 2 inner div elements. The first inner div element is to store the magnified image which would be obtained from our custom servlet. The second div element contains a close image which when clicked calls closeMagnifier() function to hide the magnifier div.

5. Toward the end of the jsp file, find the script tag and modify it as shown below:

<script language="JavaScript">
var fid = document.forms[docFormID].id;

var magnifierHidden = document.getElementById(fid+':btnMagnifierHidden');
var mval = magnifierHidden.value;
if(mval =="active"){
document.images["imgMagnifier"].src = "images/magnifierD.gif";
MapPoint('Map0', 'Magnifier');

} else {

The above code checks the value of the hidden input element that we added. If its value is active (which means current active tool is magnifier), we will activate the magnifier tool. Otherwise it will behave in a normal manner.

6. In the HighlighTool function:
a) We need to add this line outside switch statement to unselect the magnifier tool:
document.images["imgMagnifier"].src = "images/magnifier.gif";
b) And this new case statement to select the magnifier tool:

case "Magnifier":
document.images["imgMagnifier"].src = "images/magnifierD.gif";

7. Change the ButtonOut function to handle this new tool:

function ButtonOut(id, control, tool, flatimage, downimage)
var f = document.forms[docFormID];
var m = control + "_mode";
var mode = f.elements[m].value;
var imgsrc = flatimage;
var magVal = document.getElementById(':btnMagnifierHidden').value;
if(magVal =="active"){
if(tool == "Magnifier") imgsrc = downimage;
}else if (mode == tool) {
imgsrc = downimage;
var imgObj = document.getElementById(id);
if(imgObj != null) imgObj.src = imgsrc;

8. In map_functions.js file, find mapSetTool function and add this new variable right before
this function:

var isMagnifier = false;

Add this new code at the top of the mapsetTool function:

var ff = document.forms[docFormID];
var hid = document.getElementById(':btnMagnifierHidden');
if(mode=="Magnifier") {
//set the value of hidden input element
//to active
isMagnifier = true;
//change the cursor to crosshair
else {
isMagnifier = false;
//set empty value for hidden input element

In the above code, we are checking if Magnifier tool is activated. If so, we will set the value
of isMagnifier to true and that of hidden input element to active. If any other tool has been selected, we set the value of isMagnifier to false and that of hidden input element to an empty value.

9. Modify the mapPointClick function as shown below:

function mapPointClick(e) {
if (isLeftButton(e)) {
//call the custom function
sendMagnifierRequest (zleft, ztop);
else {
//post back the form = "wait";
var f = document.forms[docFormID];
postBack(Maps[divIndex].controlname, 'point');
//alert( + "\n" + zleft + "," + ztop);
return false;

Here, we are calling our custom function (that we will be looking soon) instead of posting
back the form if the magnifier tool is active.

10. Now lets take a look at the ajax.js file:

var appName = "AjaxTest";

function getHTTPObject() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
// IE
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;

//XMLHttpRequest object
var req ;

//variables to store x/y location
var ajx, ajy;

//this function sends the request
function sendMagnifierRequest(xx,yy) {
req = getHTTPObject();
ajx = mouseX;
ajy = mouseY;

//for IE, i needed to subtract 2 pixels
//to center the map more accurately
xx -= 2;
yy -= 2;
var url = "/" + appName + "/AgsServlet?x=" + xx + "&y=" + yy;
if (req != null) {"GET", url, true);
req.onreadystatechange = getResponse;

//this function processes the response
function getResponse(){

if (req.readyState == 4) {
if (req.status == 200) {

var result = req.responseText;
//position the div element
var mDiv = document.getElementById('magnifierDiv').style;
mDiv.left = ajx-100; = ajy-100;
//specify the image returned as a src
var magImg = document.getElementById('magnifierDivImg');
magImg.src = result;
//show the div
mDiv.visibility = "visible";


//this function hides the div
function closeMagnifier(){
var mDiv = document.getElementById('magnifierDiv').style;
mDiv.visibility = "hidden";

First we have specified the application name in a variable appName. Make sure to change
this variable with your web application name.

Function getHTTPObject creates and returns a new XMLHttPRequest object. Notice the difference in creating this object between IE and Mozilla.
Function sendMagnifierRequest is responsible for submiting the user click point (x/y values) to our custom servlet. In this function, we first got a new XMLHttpRequest object called req and opened a "GET" connection to our custom Servlet. We have passed the x/y values to the servlet by appending the argument value pair to the url. The following line specifies that getReponse function will be called every time he state of XMLHttpRequest object is changed:
req.onreadystatechange = getResponse;

Remember that one of the key features in Ajax is to send requests asynchronously, i.e. we won't be sitting there and waiting for the response once we submit the request. That is why we have specified the above function that will track the state of the XMLHttpRequest object and processes the response when ready.

In the getResponse function, we will check the state of the XMLHTTPRequest object and if it's value is 4 (i.e. completed) and the HTTP status of the response is 200 (OK), we will then process the response.
Remember from our previous discussion, the custom servlet simply sends back the url of the output image in a simple text format. So we will get this url from responseText property of the req object and set the url as a source to an image in a div element. We will center this DIV element at the click location and finally make it visible.

11. Finally, save the ajax.js file in the js folder of your web application.
Thats it. You are all set to test this new tool. Enjoy!!!

Thursday, August 18, 2005

Integrating AJAX with ArcGIS Server - III

Previously, we have looked at the necessary code for our custom magnifier tool. Now lets talk about how to put things together step by step.
1. First, use arcgisant tool to create a MapViewer web application.
2. Deploy the web application in a servlet container and verify that it works fine.
3. Go to this web application root directory and then to its WEB-INF/classes folder.
4. Under the classes folder, create this path: com/esri/arcgis/sample.
5. Put the and files in the sample folder.
6. Compile these 2 java classes. (You need to have servlet and arcgis server libraries in the classpath to compile the code.)
7. Next, we need to map our custom servlet in the web application. Go to WEB-INF folder and open web.xml file.
a) Add these tags to add the servlet:


b) Add these tags to map the servlet:

8. Refresh the servlet container.

This does it for the configuration of our custom servlet in the web application. Next time, we will talk about how to add the magnifier tool to the jsp page and customize the javascript code for this new tool.

Tuesday, August 16, 2005

Integrating AJAX with ArcGIS Server - II

Now lets take a look at AGSMap class mentioned earlier. Given below is the complete code for this class. Since I have added comments in between the code describing each part of the code, this should be self explanatory.

package com.esri.arcgis.sample;

import com.esri.arcgis.server.IServerConnection;
import com.esri.arcgis.server.ServerConnection;
import com.esri.arcgis.server.IServerObjectManager;
import com.esri.arcgis.server.IServerContext;

import com.esri.arcgis.carto.IMapServer;
import com.esri.arcgis.carto.IMapServerProxy;
import com.esri.arcgis.carto.IMapDescription;
import com.esri.arcgis.carto.IMapServerObjects;
import com.esri.arcgis.carto.IMapServerObjectsProxy;
import com.esri.arcgis.carto.IMap;
import com.esri.arcgis.carto.IMapProxy;
import com.esri.arcgis.carto.IMapDescriptionProxy;
import com.esri.arcgis.carto.MapDescription;
import com.esri.arcgis.carto.IImageDescription;
import com.esri.arcgis.carto.IImageDescriptionProxy;
import com.esri.arcgis.carto.ImageDescription;
import com.esri.arcgis.carto.IImageType;
import com.esri.arcgis.carto.IImageTypeProxy;
import com.esri.arcgis.carto.ImageType;
import com.esri.arcgis.carto.IImageDisplay;
import com.esri.arcgis.carto.IImageDisplayProxy;
import com.esri.arcgis.carto.ImageDisplay;
import com.esri.arcgis.carto.IMapImage;
import com.esri.arcgis.carto.IMapImageProxy;
import com.esri.arcgis.carto.MapImage;
import com.esri.arcgis.carto.IMapExtent;
import com.esri.arcgis.carto.IMapExtentProxy;
import com.esri.arcgis.carto.MapExtent;
import com.esri.arcgis.carto.IMapArea;
import com.esri.arcgis.carto.IMapAreaProxy;
import com.esri.arcgis.carto.esriImageFormat;
import com.esri.arcgis.carto.esriImageReturnType;
import com.esri.arcgis.carto.IImageResult;

import com.esri.arcgis.system.LongArray;
import com.esri.arcgis.system.ILongArray;
import com.esri.arcgis.system.ILongArrayProxy;

import com.esri.arcgis.geometry.IPoint;
import com.esri.arcgis.geometry.IPointCollection;
import com.esri.arcgis.geometry.IEnvelope;
import com.esri.arcgis.geometry.Envelope;
import com.esri.arcgis.geometry.IEnvelopeProxy;


public class AgsMap {

public synchronized static String
getImageUrl(AGSWebContext context, int x, int y){
//get IMapServer from AGSWebContext
IMapServer m_mapServer = context.getServer();
//QI to IMapServerObjects
IMapServerObjects m_mapServerObj =
new IMapServerObjectsProxy(m_mapServer);
// get IServerContext from AGSWebContext
IServerContext m_context = context.getServerContext();

IMap m_map = null;
//if there is a default map, get IMap
if (m_mapServer.getDefaultMapName() != null) {
m_map = new IMapProxy(m_mapServerObj.getMap(
} else return null;

//get Default MapDescription from AGSWebContext
IMapDescription m_mapDesc = context.getMapDescription(
create a new ImageType and set the properties
we are getting the image url, so make sure to
specify output directory in ArcCatalog
for the server object config being used in
this application
IImageType m_imageType = new IImageTypeProxy(

//create a new IImageDisplay
//set width and height same as that of the Map Control
//because we will be using it to convert pixel
//point to Map point
IImageDisplay m_imageDisplay = new IImageDisplayProxy(

//set the above IImageDisplay and IImageType
// to IImageDescription
IImageDescription m_imageDesc = new IImageDescriptionProxy(

//convert pixel point into map point
//notice that we are using the above map
//description and image description
// in mapserver.toMapPoints method
ILongArray longArrayX = new ILongArrayProxy(
longArrayX.insert(0, x-10);
ILongArray longArrayY = new ILongArrayProxy(
longArrayY.insert(0, y+10);
IPointCollection pointColl = m_mapServer.toMapPoints(
IPoint point1 = null;
IPoint point2 = null;
if (pointColl.getPointCount() > 0) {
point1 = pointColl.getPoint(0);
point2 = pointColl.getPoint(1);

//generate a small envelope based on map points
IEnvelope env = new IEnvelopeProxy(

//reset the Image size to 200X200
//this is the size of the magnified image

//set the new MapExtent based on the above envelope
IMapExtent mapExtent = new IMapExtentProxy(

//create a new map description and set above
//extent and default LayerDescriptions to it
IMapDescription m_mapDesc1 = new IMapDescriptionProxy(
IMapArea mapArea = new IMapAreaProxy(mapExtent);

//export the map image and get its URL
IMapImage mapImage = m_mapServer.exportMapImage(
m_mapDesc1, m_imageDesc);
String url = mapImage.getURL();
//finally release the context
return url;
}catch (Exception ex){
return null;

Integrating AJAX with ArcGIS Server - I

As I mentioned previously, one of the ways to implement Ajax in the ArcGIS Server Java application is by creating a custom Servlet. We can then write Javascript code to submit client request to this custom Servlet using the XMLHttpRequest object. The servlet in return will generate the response which is again processed by the custom Javascript code on the client side.

Lets talk about how to create a Magnifier tool in ArcGIS Server MapViewer template by creating a custom servlet. First, we will pass the user click point (X/Y values) to our custom servlet. The custom Servlet will then use ArcObjects to generate the magnified image for that location. That sounds easy, but how can we get the server object properties (like server connection, map properties etc.) already stored in Java ADF in our custom Servlet? They are required for us to be able generate the map image using our custom ArcObjects code. The answer is the AGSWebContext object which hosts all ArcObjects for the server object.

Getting AGSWebContext in a Servlet is pretty simple. All we need to do is first get the WebSession attribute from session and then get AGSWebContext object from WebSession. Once we get AGSWebContext object, we need to
1. call activate method to hydrate the current properties of a pooled server object. (We are using pooled server object because we want to be able to quickly generate image and release the server object back. )
2. pass the AgsWebContext to another class names AgsMap which will generate the image.
3. call passivate method to release the server object back to the pool.

I will discuss the AgsMap class next time but for now here is the complete code for the custom Servlet:

package com.esri.arcgis.sample;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public final class AgsServlet
extends HttpServlet {

private ServletConfig servletConfig = null;

public void destroy() {
servletConfig = null;

public ServletConfig getServletConfig() {

return (this.servletConfig);


public String getServletInfo() {

return (this.getClass().getName());


public void init(ServletConfig servletConfig)
throws ServletException {

this.servletConfig = servletConfig;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws, ServletException {
HttpSession session = request.getSession(true);
int x = Integer.parseInt(
int y = Integer.parseInt(
WebSession wsession = (WebSession)
session.getAttribute(WebSession.SESSION_ATTRIBUTE_NAME );
String url=null;
if(wsession!=null) {
AGSWebContext context = (AGSWebContext)
url = AgsMap.getImageUrl(context, x, y);
response.setContentType("text/html"); out=response.getWriter();

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws, ServletException {
doGet(request, response);


Sunday, August 14, 2005

AJAXizing ArcGIS Server MapViewer Template

Being a great Ajax fan, I am excited to see big companies like Google, Microsoft, Oracle, Sun promoting it big time. ESRI is also planning to implement Ajax in the 9.2 Server ADF. I have developed a few tools myself integrating Ajax with the current ArcGIS Server MapViewer Java template and I think it's really cool and fast.
Let me describe one such tool a little bit more. It is the magnifier tool just like in ArcMap to get the more detailed floating map for a particular location in the main map. Normally with the server applications, you need to submit the form and reload the entire webpage to get the new data. Using the Ajax technique, however, we can request the magnified map behind the scene and thus it will eliminate the need to reload the entire website. Since there is no need to render the entire website, which could be costly timewise, there will be a significant improvement in performance and thus the user experience will be much closer to that of the desktop applications.
Greg Murray, Tor Norbye, Ed Burns have described 3 different techniques to use JSF application like the ArcGIS Server MapViewer with ajax. The first 2 techniques require creating custom components in JSF in such a way that the users of such components need not implement their own javascript code. Tor Norbye has described the design detail for creating an Ajax auto-complete component here.
I have, however, used the third technique because of its simplicity. With this technique, I didn't need to create my own custom JSF components. I had rather created a custom Servlet that would be responsible for generating the response for each request.
In my upcoming blogs, I will describe the code behind this tool.

Remote ArcIMS server in a frameless html viewer

There have been some questions about how to run Frameless HTML Viewer in a separate web server and access a remote ArcIMS Server from it. Javascript has the same origin policy which prevents a webpage loaded from one server communicating to a different server for security reason. To work around this problem in the HTML Viewer, there is a property in the Servlet Connector called redirect which allows forwarding the ArcXML requests to the remote ArcIMS server. Thus by installing the Servlet Connector on a web server and setting it to redirect to any remote server, we can 'fool' the Javascript to think that it's loading the response from the same server.
I initially thought this would work for the frameless viewer too. On further testing, it appeared that the redirection in servlet connector works only with the form based requests.
There is still another work around though. This is to create a web application in jsp/ASP/Servlet etc and deploy it on the web server. The web application needs to simply forward the ArcXML requests to the remote ArcIMS Server and get back the responses. It is pretty simple to create such application using one of the connectors.
For instance, here is the JSP code to do this:

<%@ page import="java.util.*" %>
<%@ page import="*" %>
<%@ page import="" %>
String server = "";
String service = "ESRI_World";
ConnectionProxy mcp = new ConnectionProxy();
int reqLength = request.getContentLength();
byte[] reqByte;
if (reqLength > 0) {
reqByte = new byte[reqLength];
int data = 1;
int offset = 0;
while (data > 0) {
data = request.getInputStream().read(reqByte, offset,reqLength - offset);
offset = offset+ data;
String axl = new String(reqByte);
String res = mcp.send(axl);
} else

Friday, August 12, 2005

Ajax and HTML Viewer

I have lately been playing around with JSF and Ajax. I will be writing more on these topics soon. For now though, a little bit on Ajax.
Ajax, if you do not know about it yet, is a concept rather than a tool. Using a little known (until recently) Javascript object called XMLHTTPRequest, one can send asynchronous requests to the server and get data in the background so that the web content can be updated dynamically without the need to reload the entire website. There are other things about ajax and you can get more descriptions here:

Think about it, ArcIMS HTML Viewer is partially (of course, not completely) an ajax application too. Just like a typical ajax application, it receives the data from the server in the background and updates the webpages dynamically. There is no reloading of the entire website for each and every requests. Of course, it uses frames to achieve this.
Many ArcIMS developers have wondered about how to create a frameless HTML Viewer. Ajax is the way to go and here is a sample application:
Here is one more example of ajax in action: