This section takes you through the creation and deployment of a simple JSP application, Game of Eight. In the sample application, Game of Eight a jumbled magic square with numbers from 1 to 8 is ordered using an HTML client. The program checks for the right order every time a tile is moved. When all the tiles are ordered, a congratulatory message, along with the time taken to solve the game, is displayed.

The walkthrough demonstrates the following:

  • Creating the Project/Directory structure
  • Writing a Java File
  • Writing a JSP page
  • Deploying the application on the Dekoh Desktop
  • Launching the JSP

In this sample, a Windows platform is assumed. To work on any other platform, follow the required file conventions on that platform.

The components used in this sample are:

  • gameofeight.jsp The client view of the game. It collects information on the sequence of tiles after every move, refers the bean to check against the required order, and reports the result to the client. The JSP includes HTML tags that compose the tiles of the magic square. Image files (*.gif) are used to compose the squares
  • Eight.java Java code that embeds routine methods to check sequence every time a tile is moved and a new square is formed. It matches the sequence to the correct ordered square
  • Image files Gif files used to compose the HTML front end

Creating a Directory Structure

  1. Create the following directory structure under C:/ drive.
GameofEight
- /src/gameofeights
- /im
- /WEB-INF/classes

Adding Files to your Directories

  1. JSPs deliver dynamic content to Web clients (standard Web browsers). Use the following code to create a simple JSP that looks up Eight.java class.
  2. Create a JSP page. Name the file as gameofeight.jsp, save it under the root directory, GameofEight and copy the following code into the file.
<html>
<head>
<title>Game of Eight : The JSP version</title></head>
<body bgcolor=#ffffff>
<font face="Verdana, Sans-serif" size=5 color="#ff3333">
<b>Eight puzzle: Using Jsp</b>
</font>
<hr size=1 color="#000099">
<font face="Verdana, Sans-serif" size=2>
<p>

<%@ page import="gameofeights.*" %>
<jsp:useBean id="game" class="gameofeights.Eight" scope="session" />

<% String startagain = request.getParameter("startagain");
	if (startagain!=null)
		if (startagain.equals("true"))
			game.initialize();
	    String message = null;
	    String rowVal=request.getParameter("rowVal");
	    String colVal=request.getParameter("colVal");

	    if (rowVal!=null) {

	 	message=game.moveTile(rowVal,colVal);

	    }

	    String[][] gifarray=game.getArray();
	    boolean gamestatus =true;
	    if ( (message!=null) && (message.equals("won")) ) {
		gamestatus=false;

%>			
<p>Congratulations ! You won<br>		
<%	    }%>
<table width=150 cellspacing=0 cellpadding=1 border=3  bgcolor=#ffffcc>
<%	    for (int i=0;i<3;i++) {%>
		<tr>
<%		for (int j=0;j<3;j++) { %>
		    <td>
<%		    if (gamestatus) { %>
	              <a href="gameofeight.jsp?rowVal=<%=i%>&colVal=<%=j%>">
<%		    } %>
		    <img src="im/<%=gifarray[i][j]%>" border=0></a>
		    </td>
<%		} %>
	        </tr>
<%	    } %>

</table>

<%	    if (!gamestatus)  {%>
		<br><br>
		     <a href="gameofeight.jsp?startagain=true">Start Again?</a>
<% 	    } %>

</p>
<hr size=1 color="#000099">
</div>
<font face="verdana, sans-serif" size=1>
<b>Aim:</b> Move the tiles to rearrange the numbers in sequence:<br><br>

1 2 3<br>
4 5 6<br>
7 8 &nbsp; <br><br>

<b>Moving the tiles:</b> A tile is moveable if it is adjacent to the empty square.<br>
To move a tile, click on it. The tile will move into the empty square.<br>
Clicking on a non-moveable tile will do nothing.
</body>
</html>
  1. Under the im directory, save nine gif files containing the numbers 1 to 8 and, a blank image – for each cell in the game. You may also pick the images from the zip provided below.
  2. Under the GameofEight/src/gameofeights directory, create a java file called Eight.java and place the following code in it.
package gameofeights;
import java.util.Vector;
public class Eight extends Object
{
	private int array[][];
	private int solution[][];
	private String gifArray[][];
	private int row, col;
	private boolean moved;

	public Eight()
	{
		array = new int[3][3];
		solution = new int[3][3];
		gifArray = new String[3][3];
		moved = true;
		initArray();
	}

	public String moveTile( String rowVal, String colVal )
	{
		/* Time implementation
		if( count == 0 )
			startTime=System.currentTimeMillis();
		*/
		int numRow, numCol;
		try
		{
			numRow = Integer.parseInt(rowVal);
			numCol = Integer.parseInt(colVal);
		}
		catch( NumberFormatException exc )
		{
			return exc.toString();
		}

		if( isMoveable(array[numRow][numCol]) )
		{
			swap(array[numRow][numCol]);
			moved = true;
			//count++;
			if( won() )
			{
				//timeTaken = System.currentTimeMillis()-startTime;
				return new String("won");
			}
			return new String("moved");
		}
		moved = false;
		return new String("not moved");
	}

	/*
	public String getTime()
	{
		return new String(""+timeTaken/1000);
	}

	*/
	public String[][] getArray()
	{
		if(!moved)
			return gifArray;
		for(int i=0; i<3; i++)
			for( int j=0; j<3; j++ )
				gifArray[i][j] = new String( array[i][j] +".gif");
		return gifArray;
	}

	/*
	public int getMoveCount()
	{
		return count;
	}
	*/

	private boolean won()
	{
		for(int i=0; i<3; i++)
			for( int j=0; j<3; j++ )
				if(array[i][j] != solution[i][j])
					return false;
		return true;
	}
	private void initArray()
	{
		solution[0][0]=1;
		solution[0][1]=2;
		solution[0][2]=3;
		solution[1][0]=4;
		solution[1][1]=5;
		solution[1][2]=6;
		solution[2][0]=7;
		solution[2][1]=8;
		solution[2][2]=0;

		// to be implemented: Random generation

		array[0][0]=3;
		array[0][1]=1;
		array[0][2]=7;
		array[1][0]=2;
		array[1][1]=5;
		array[1][2]=4;
		array[2][0]=8;
		array[2][1]=6;
		array[2][2]=0;
	}

	private boolean isMoveable( int num )
	{
		row = getRow(num);
		col = getCol(num);
		return (	( row-1 >= 0 && array[row-1][col] == 0 )	||
				( row+1 < 3 && array[row+1][col] == 0 )		||
				( col-1 >=0 && array[row][col-1] == 0 )		||
				( col+1 < 3 && array[row][col+1] == 0 )
			);
	}

	private int getRow( int num )
	{
		for(int i=0; i<3; i++)
			for( int j=0; j<3; j++ )
				if( array[i][j] == num )
					return i;
		return -1;
	}

	private int getCol( int num )

	{
		for(int i=0; i<3; i++)
			for( int j=0; j<3; j++ )
				if( array[i][j] == num )
					return j;
		return -1;
	}

	private void swap( int num )
	{
		int blankrow = getRow(0);
		int blankcol = getCol(0);
		array[blankrow][blankcol] = num;
		array[row][col] = 0;
	}

	public void initialize()
	{
		array[0][0]=3;
		array[0][1]=1;
		array[0][2]=7;
		array[1][0]=2;
		array[1][1]=5;
		array[1][2]=4;
		array[2][0]=8;
		array[2][1]=6;
		array[2][2]=0;
	}
}
  1. Under the GameofEight/Web-INF directory, create a new file, copy the following code into it and save it as web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <icon>
    <small-icon />
    <large-icon />
  </icon>
  <display-name>GameofEightWeb</display-name>
  <description>No Description</description>
  <servlet>
    <servlet-name>gameofeight.jsp</servlet-name>
    <display-name>gameofeight.jsp</display-name>
    <description>No Description</description>
    <jsp-file>gameofeight.jsp</jsp-file>
  </servlet>
    <session-config>
    <session-timeout>-1</session-timeout>
  </session-config>
</web-app>

Compiling the Java File

  1. Ensure that you set the PATH correctly to use the correct version of JDK ( JDK 1.5 or higher).
  2. At the command prompt, navigate to the GameofEight directory.
  3. Compile the java source using the command
javac -d WEB-INF/classes src/gameofeights/Eight.java
  1. Executing this command compiles the java source file, Eight.java and stores the compiled classes under the WEB-INF/classes directory. Check the directory to ensure that the file has been compiled.
  2. Your application is now ready to be deployed.

Deploying the Application

  1. At the command prompt, navigate to the C:/Dekoh/server/bin directory by typing
cd c:\Dekoh\server\bin
  1. Start the Dekoh Desktop using the dekoh_shell.bat command.
  2. At the LWT prompt, type
deploy c:\GameofEight
  1. To confirm whether the application has been successfully deployed, type
list *
in the command prompt, and check whether GameofEight is displayed in the list that comes up.

Note: If you have the Dekoh Desktop already running, you must shut it down before you use the command, dekoh_shell.bat to restart the Server.

Running the JSP Application

  1. To run the JSP, open your default browser and run the JSP by entering http://localhost:8181/GameofEight/gameofeight.jsp.
In this URL, the Web Module name (GameofEight) is the context root of the web application. The game of eight is ready for you to play.

Debugging Your Application

This chapter discusses how to debug the JSP application you just built using IDEs such as IntelliJIDEA and Eclipse SDK. In the following sections, we use the Debugger to:

  • Debug JavaServer Pages remotely
  • View the trace for the specific thread
  • View only source-specific threads for clarity of diagnosis
  • Drill down into objects and watch variables as the code executes

Setting the Java Debug Option

  1. Set the Java debug option in the dekoh_shell.bat or dekoh_shell.sh files by adding
-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777
to the command,
java -server -cp %CLASSPATH% %COMPILER_OPTIONS% %DATEPARSING% %REDIRECTSTREAMS% com.pramati.web.lwt.LWWebServer -
nodedir ../nodes/default -httpport 8181 %NOSHELL%

Debug Using Eclipse

  1. To debug your application using Eclipse, you will first need to create your GameofEight project in Eclipse.
  2. To start the application in the debug mode, click on Run > Debug.. from the main menu. This brings up the Debug dialog where you can configure the debugger settings.
Note: To use remote debugging, you should be using a Java VM that supports this feature
  1. Start the debugger using a remote launch configuration and specify the address and port of the remote computer. To do this, right click on the Remote Java Application on the left tab and select New. Select the project as GameofEight, and change the port number to 7777.
  2. Click on Debug to start the Dekoh Desktop in the Debug mode.
  3. Deploy the GameofEight application from the command prompt by typing the following commands:
    1. Navigate to the C:/Dekoh/server/bin directory by typing
cd c:\Dekoh\server\bin
    1. Start the Dekoh Desktop using the dekoh_shell.bat command.
    2. At the LWT prompt, type
deploy c:\GameofEight
  1. Set a breakpoint on an executable line of code for the execution to stop when the control flow reaches the line on which you have set the breakpoint. In this case, inside the file, Eight.java, set a breakpoint in the line
for(int i=0; i<3; i++)
inside the getRow method.
  1. Run the JSP by entering http://localhost:8181/GameofEight/gameofeight.jsp in your default browser. Start playing by moving the tile positions.
  2. Watch the application being debugged in the Eclipse IDE. The Variables tab displays the stack at the point of execution. You can now also perform actions such as step into, step out, changing current thread etc.

Debug Using IntelliJIDEA

  1. To debug your application using IntelliJIDEA, you will first need to create your GameofEight project in IntelliJIDEA.
  2. To start the application in the debug mode, click on Run > Debug.. from the main menu. This brings up the Debug dialog where you can configure the debugger settings.
Note: To use remote debugging, you should be using a Java VM that supports this feature
  1. Start the debugger using a remote launch configuration and specify the address and port of the remote computer. To do this, right click on the Remote tab and select Add new Configuration. Select the Name as Dekoh Desktop, and change the port number to 7777.
  2. Click on Debug to start the Dekoh Desktop in the Debug mode.
  3. Deploy the GameofEight application from the command prompt by typing the following commands:
    1. Navigate to the C:/Dekoh/server/bin directory by typing
cd c:\Dekoh\server\bin
    1. Start the Dekoh using the dekoh_shell.bat command.
    2. At the LWT prompt, type
deploy c:\GameofEight
  1. Set a breakpoint on an executable line of code for the execution to stop when the control flow reaches the line on which you have set the breakpoint. In this case, set the breakpoint in the line
for(int i=0; i<3; i++)
inside the getRow method.
  1. Run the JSP by entering http://localhost:8181/GameofEight/gameofeight.jsp in your default browser. Start playing by moving the tile positions.
  2. Watch the application being debugged in the IntelliJIDEA IDE. Use the Threads tab to view the different threads and stacks at the points of execution. You can also perform actions such as step into, step out, changing current thread etc.

Distributing your Application

Now that you have your application running, you may want to distribute it to end users who have installed Dekoh Desktop, and will like to work with your application.

To make your application distributable to the end user:

  1. Use the pre-compiled JSP Pages that were created when you deployed the application
OR Compile the JSP Pages specifically using ANT
  1. Save the component.xml file
  2. Package the application into deployable archives.

Using the Compiled JSP Pages

  1. When you deploy the JSP application the first time, the compiled classes are stored under the WEB-INF/classes directory. You may use these compiled classes to build your archive.

Compiling the JSP Application Using ANT

  1. To compile the JSP Pages, you can also use ANT. Before using ANT, ensure that you have set the path correctly for ANT.
  2. Copy the following code into a new file.
LIB_DIR = C:\\Dekoh\\server\\lib
pramati.lwt.jar = ${LIB_DIR}/pramati/pramati_web_lwt.jar
ant.class.path = ${pramati.lwt.jar}
app.path=C:/GameOfEight
SERVLET_ROOT = ${app.path}
web.xml.file = ${app.path}/WEB-INF/web.xml
exclude.jsp.list = \"\"
includes.jsp.list =
project.class.path = ${ant.class.path}:\
${SERVLET_ROOT}/WEB_INF/classes:\
  1. Change the application path
app.path=C:/GameOfEight 
to point to your GameofEight root directory.
  1. Save the file as das-jsp-compile.props.
  2. Copy the following code into a blank file and save it as das-jsp-compile.xml. Ensure to save this file in the same directory as das-jsp-compile.props.
<?xml version="1.0" encoding="UTF-8"?>
<project name="AntShell" default="instrument">
    <property file="das-jsp-compile.props"/>
    <taskdef classname="com.pramati.tools.ant.AntTaskHandlerJSPCompiler" name="jspc">
        <classpath id="jspc.classpath">
            <pathelement path="${ant.class.path}"/>
        </classpath>
    </taskdef>
    <taskdef classname="com.pramati.tools.ant.AntTaskHandlerInstrument" name="instrument">
        <classpath id="instrument.classpath">
            <pathelement path="${ant.class.path}"/>
        </classpath>
    </taskdef>
   <target name="parse">
        <jspc appRoot="${SERVLET_ROOT}" validateXML="true"
              targetWebXmlPath="${web.xml.file}" includes="${includes.jsp.list}" excludes="${exclude.jsp.list}"
              outputDir="${SERVLET_ROOT}/WEB-INF/src">
            <classpath>
                <pathelement path="${project.class.path}"/>
            </classpath>
        </jspc>
    </target>
    <target name="compile" depends="parse">
        <mkdir dir="${SERVLET_ROOT}/WEB-INF/classes"/>
        <mkdir dir="${SERVLET_ROOT}/WEB-INF/lib"/>
        <javac destdir="${SERVLET_ROOT}/WEB-INF/classes" optimize="off" debug="on" failonerror="false"
               srcdir="${SERVLET_ROOT}/WEB-INF/src" memoryinitialsize="256m" memorymaximumsize="512m" fork="yes">
            <classpath>
                <pathelement path="${project.class.path}"/>
            </classpath>
        </javac>
    </target>
    <target name="instrument" depends="compile">
        <instrument srcDir="${SERVLET_ROOT}/WEB-INF/src" classDir="${SERVLET_ROOT}/WEB-INF/classes"/>
    </target>
</project>
  1. At the command prompt, type
ant -f <full path to das-jsp-compile.xml>
to compile the file, das-jsp-compile.xml

Saving component.xml file

  1. Copy the following code into a new file, and save the file in the GameofEight root directory. Name the file as component.xml. This code contains some component-specific information for the application you want to distribute. The version number in the component.xml file helps the user keep track of the version of the application.
  <?xml version="1.0" encoding="UTF-8" ?> 
- <component xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.dekoh.com/xmlns/component http://www.dekoh.com/schemas/component.xsd" xmlns="http://www.dekoh.com/xmlns/component" enabled="true">
  <id>http://www.dekoh.com/ns/component/app/gameofeight</id> 
  <version>1.0</version> 
  <type>application</type> 
  <display-name>GameOfEight</display-name> 
  <description>Order a magic square jumble with numbers from 1 to It checks for the right order every time a tile is moved. When all the tiles are ordered, a success message shows up along with the time taken to solve the game.</description> 
  </component>
The version manager in Dekoh compares your version against the currently available version of the application. This will either tell you that no upgrade is needed, or that an upgrade is recommended.
  1. If you want to define more elements in your component.xml file, use the component.xsd file. The component.xsd file is defined as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema xmlns:component="http://www.dekoh.com/xmlns/component"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified"
           targetNamespace="http://www.dekoh.com/xmlns/component">
    <xs:element name="callback-classes">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="component:callback-class" maxOccurs="unbounded" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="dependencies">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="component:dependency" maxOccurs="unbounded" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="component">
        <xs:complexType>
            <xs:all>
                <xs:element ref="component:id"/>
                <xs:element ref="component:version"/>
                <xs:element ref="component:type"/>
                <xs:element ref="component:display-name" minOccurs="0"/>
                <xs:element ref="component:description" minOccurs="0"/>
                <xs:element ref="component:updateurl" minOccurs="0"/>
                <xs:element ref="component:downloadurl" minOccurs="0"/>
                <xs:element ref="component:dependencies" minOccurs="0"/>
                <xs:element ref="component:callback-classes" minOccurs="0"/>
            </xs:all>
            <xs:attribute name="enabled" use="optional">
                <xs:simpleType>
                    <xs:restriction base="xs:boolean"/>
                </xs:simpleType>
            </xs:attribute>
            <xs:attribute name="version" use="optional">
                <xs:simpleType>
                    <xs:restriction base="xs:string"/>
                </xs:simpleType>
            </xs:attribute>
        </xs:complexType>
    </xs:element>
    <xs:element name="dependency">
        <xs:complexType>
            <xs:all>
                <xs:element ref="component:id"/>
                <xs:element ref="component:maxversion"/>
                <xs:element ref="component:minversion"/>
                <xs:element ref="component:updateurl"/>
            </xs:all>
            <xs:attribute name="type" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="description" type="xs:string"/>
    <xs:element name="id" type="xs:string"/>
    <xs:element name="maxversion" type="xs:string"/>
    <xs:element name="minversion" type="xs:string"/>
    <xs:element name="display-name" type="xs:string"/>
    <xs:element name="type" type="xs:string"/>
    <xs:element name="updateurl" type="xs:string"/>
    <xs:element name="downloadurl" type="xs:string"/>
    <xs:element name="callback-class" type="xs:string"/>
    <xs:element name="version" type="xs:string"/>
</xs:schema>

Packaging the Application

  1. At the command prompt, package the GameofEight application into a WAR by typing the command
jar -cfv GameOfEight.war *.jsp im WEB-INF web.xml
  1. Your application is now ready to be distributed for the users to deploy.

Attachments

0.gif Info on 0.gif 43 bytes
im.zip Info on im.zip 12722 bytes