The second part of the wireless development tutorial - establish an end-to-end JAVA application

xiaoxiao2021-03-06  37

Author: Jonathan Knudsen

Translation: flybean

March 2002

Download: HitServlet.java Hitmidlet.java

In the first part of this tutorial, you have learned how to write a simple Java [TM] 2 micro version (J2ME [TM]) application. J2ME [TM] application, a MIDLET program is designed for the mobile information device protocol subset. This protocol is a specification in J2ME. Now I am in exciting moments, you will expand your horizons. You will learn how to write and publish a servlet, and mount the servlet with a MIDlet program. When you read your article, you will master all knowledge of the development end-to-end wireless Java application.

This article has two versions, you can choose according to the servlet development platform you want:

Tomcat is a reference implementation for a free Java Servlet and JavaServer Pages (JSP) specification. Although it is not a product quality server, it is undeniable, it is an extremely excellent servlet development and test platform. Java [TM] 2, Enterprise Edition (J2EE [TM]) Reference Implementation (J2EE RI, J2EE Reference Implementation) The server fully implements J2EE specification. Like Tomcat, it does not try to become a server with product quality. However, it is a good prototype for developers learning, testing, and experiments. Of course, you will not be troubled by the price. J2EE RI servers are free, freely downloadable.

Of course, each server has two aspects. For servlet development, Tomcat is easy to use. However, its ability is limited to servlet and JSP. Compared to this, J2EE RI servers realize all areas of J2EE technology, including servlet, JSP, EJB, JMS, JNDI, and more.

The demonstrations you are now read now is to use Tomcat to develop servlet development. Click here to read the J2EE RI server version of this article.

Install and run Tomcat

Tomcat is released in the form of a zip package, you can download from the Apache Jakarta project. When writing this article, its version is 4.0.2.

Tomcat's installation process is very simple, and you have to do it just to download the file. You can put it on any place you want to put. I unpack it to the root-class directory, c: /jakarta-tomcat-4.0.2/.

Tomcat itself is written in Java. To run it, you need to tell it to the installation location of J2SE. You can write the J2SE installation location to the environment variable Java_home to complete this work. On my machine, the value of the environment variable java_home is C: /JDK1.3.1.

In order to run Tomcat, you need to open a command window. Go to Tomcat's bin directory, type STARTUP and enter. The system will jump out of a new window, and some initialization information is displayed.

Tomcat initialization information

You can use your browser to check if Tomcat is really running: Try Open URL http: // localhost: 8080 / to see what happened. If Tomcat is running normally, you should see a default page of Tomcat, there are some links to servlet and JSP examples.

When Tomcat is closed, an additional command window is opened. Enter the Tomcat's bin directory and run the shutdown command.

This way to start and stop Tomcat is slightly awkward. I suggest you create a Windows shortcut to run the Startup and Shutdown commands. Write Servle Source Code

Writing code for your servlet is very similar to writing other Java source code: Create a Java source file using the text editor you selected. In this example, you will write a very simple servlet, named HitServlet. The source code is shown below. HitServlet simply counts the number of times it is called, and will send information containing this statistic to the client. (It is not a thread safe, there is nothing to do here.)

Import javax.servlet.http. *;

Import javax.servlet. *;

Import java.io. *;

Public class HitServlet Extends httpservlet {

PRIVATE INT MCOUNT;

Public void doget (httpservletRequest Request,

Httpservletresponse response

Throws servletexception, ioException {

String message = "HITS:" mcount;

Response.setContentType ("text / plain");

Response.setContentLength (Message.Length ());

PrintWriter out = response.getwriter ();

Out.println (MESSAGE);

}

}

Later, you will build a web application with a special directory structure. With this directory structure, the server can easily find the various parts required for the application. From now on, the Believe Find (Translator Note: Don't ask why), save the source code as a file under the Tomcat root directory, named WebApps / MIDP / Web-INF / CLASSEES / HITSERVLET.JAVA. (Now continue to create a MIDP directory and its subdirectory.)

Compiling servlet

In addition to an important change, compiling the servlet code is very close to the compilation process of other Java development. Since the Servlet API is not a core part of the J2SE platform, you need to add it to ClassPath before compiling the servlet.

The common / lib / servlet.jar file contains the servlet API in the Tomcat root directory. You only need to simply add this file to the ClassPath, you can compile HitServlet.java using Javac. As the sample demonstrated by the Windows example, you can edit ClassPath in the system properties, or in the command line:

C: /> set classpath = / jakarta-tomcat-4.0.2 / common / lib / servlet.jar

C: /> javac hitservlet.java

Release servlet

In order to release your servlet, you must first understand some things about the web application. A web application is a set of static contents such as HML, images, servlets, and other resources that can be accessed through the web interface. Enter your WebApps directory in your Tomcat installation directory, you can see some files (or directories), for example: Examples and Manager. We will create a new web app and put our servlet inside.

First, we create a web application. You have established a new directory called MIDP in the WebApps directory, which will be the directory you saved the servlet source code. Now you need to edit a profile of Tomcat, so tomcat knows this new web application. Use the text editor to open the file conf / server.xml. In this document, web applications are called contexts. Use the scroll bar to find the Context project of the Examples web app, similar to the following:

Debug = "0" privileged = "true" />

Copy the entire project for your new web application. Modify the corresponding name to MIDP and join the reloadable property:

Debug = "0" reloadable = "true" privileged = "true" />

Put the MIDP context item in the Examples context item, save the file.

The above steps are to map the HTTP request to the web application in a specific directory. Any HTTP request starting with "/ MIDP" (PATH) will clearly transfer to web applications where WebApps / MIDP (DocBase). The reloadable property is great for debugging: it tells Tomcat to automatically reload any of the servlet classes you modified so you don't have to restart the server.

Now you have created a web application and enriched content. The web application has a standard directory structure, which is required by the Servlet specification. Here, we will not in depth this problem. The required part of the web application is a web.xml file, which describes the different part of the web application. It is located in the standard directory of each web application, usually stored as web-inf / web.xml.

You should now create a web.xml file for your new app. You want the world outside to visit your servlet. You know the class name of the servlet: HitServlet, and you want to use a similar / HITS path. Note: The path to the servlet is relative to the path to the web application, so the full path to the servlet will be http: // localhost: 8080 / midp / hits. Copy the text (or download) and save it as a webApps / midp / web-inf / web.xml file in the Tomcat root:

Public "- // Sun microsystems, Inc.//dtd Web Application 2.3 // en"

"http://java.sun.com/dtd/web-app_2_3.dtd">

Bob

HitServlet

Bob

/ hits

This file tells Tomcat to map the servlet named HitServlet to the path / HITS. Servlet-name is the internal element of Web.xml, which links the servlet element with the servlet-mapping element. Name BOB is just a friendly example, you can choose any name you want.

You should remember that you have stored your servlet source code in the standard directory named Classes named in the web -ince. This directory is Tomcat expects to discover the directory of the servlet class file, so when you compile the source code, the servlet class is stored in the correct position.

Now your servlet has been published in the new web application you created. However, please note that you must restart Tomcat so that it is recognized that you make changes to the Server.xml file.

Open the browser, browse http: // localhost: 8080 / midp / hits, you can test your work you have done. You should be able to see the output of the HitServlet. Re-load the page several times, observe the growth of the number of hits.

For More Information, See Java Servlet Technology, Part of The J2EE TUTORIAL.

For more information on servlet development, please see Java Servlet Technology. This article is part of the J2EE tutorial.

Turn on MIDlet with servlet

This part is very interesting. Now you have a development environment that supports both MIDP and supports servlet. You will turn on these two worlds, create a peer-to-end Java app. With HTTP, MIDlet can connect the entire world, and the servlet you have written will allow the entire world to visit. Therefore, MIDLET is connected to servlet is a very simple thing.

Run KToolbar (part of J2Mewtk), open the MIDlet project created by the first part of this tutorial. You will have a new MIDlet, which will connect to your servlet to get its output and display. If you haven't created a J2ME Wireless Toolkit project, return to the first part and start now. The entire source code for connecting the MIDlet connected to the HitServlet is given below.

Import java.io. *;

Import javax.microedition.io. *;

Import javax.microedition.lcdui. *;

Import javax.microedition.midlet. *;

Public class hitmidlet

Extends MIDlet

Implements commandListener {

Private display mdisplay;

Private form mmainform;

Private stringItem mimentageit;

Private Command MexitCommand, MConnectCommand;

Public hitmidlet () {

Mmainform = New form ("HitmIdlet");

MMessageItem = New stringItem (NULL, "");

MexitCommand = New Command ("EXIT", Command.exit, 0);

MConnectCommand = New Command ("Connect",

Command.screen, 0);

Mmainform.Append (MMessageItem);

Mmainform.Addcommand (MexitCommand);

Mmainform.Addcommand (MconnectCommand);

Mmainform.SetCommandListener (this);

}

Public void startapp () {

Mdisplay = display.getdisplay (this);

Mdisplay.SetCurrent (mmainform);

}

Public void pauseapp () {}

Public void destroyApp (boolean unconditional) {}

Public void CommandAction (Command C, Displayable S) {

IF (c == MexitCommand)

NotifyDestroyed ();

Else if (c == mconnectCommand) {

Form WaitForm = New Form ("Waiting ...");

Mdisplay.SetCurrent (waitform);

Thread t = new thread () {

Public void run () {

CONNECT ();

}

}

T.Start ();

}

}

Private void connection () {

HTTPConnection HC = NULL;

InputStream in = NULL;

String Url = getAppproperty ("Hellomidlet.URL");

Try {

HC = (httpConnection) Connector.Open (URL);

IN = hc.openputstream ();

INT contentLength = (int) hc.getlength ();

Byte [] raw = new byte [contentLength];

INT length = in.read (raw);

In.Close ();

Hc.close ();

// Show the response to the user.

String s = new string (RAW, 0, Length);

MMessageItem.SetText (s);

}

Catch (IOException IoE) {

MMessageItem.Settext (IOE.TOSTRING ());

}

Mdisplay.SetCurrent (mmainform);

}

}

HitmIdlet's home screen is similar to Hellomidlet, but it includes two commands: exit and connect. Connect Starts a stand-alone thread and calls the connect () method, which handles network connection and acquisition results.

Copy the code (or download) to your editor and save it as a file called Hitmidlet.java in the Apps / Hellosuite / src directory in the J2mewtk root directory.

You need to complete other two configurations before Hitmidlet work. First, you need to tell J2MEWTK in the case of this new MIDlet. Click Settings ... and select the MIDlets page. Click Add and fill in "HitmIdlet" in the MIDlet name and class name. You can make the icon items. Click OK, you will see Hellomidlet and HitmIdlets. Next, you need to define a system properties that is the URL of the Hellomidlet as its network connection (this property is taken out in the third row of Connect ()). In J2MEWTK, click Settings ... and select the user defined page. Click the Add button. Fill in the property name to hellomidlet.URL, its value should be the URL that calls HitServlet, which is the URL used in your browser when you test servlet. After completing, click OK to close the project setting window.

Now, in J2MEWTK, click Build to construct this project. Suppose you have not got any error messages, you can now prepare to test this app. First make sure your server is in operation. Then in J2MEWTK, click RUN, select HitmIdlet. Select the connect command. If everything is normal, HitmIdlet will call the HitServlet and display it on the device emulator screen:

success!

Development precautions

Now, you have created your own web application, you can easily modify and test HitServlet; just change the source code and recompile. When you call servlet from your browser or hellomidlet, Tomcat will use the new version of Servlet (Remember the RELOADABLE attribute in Tomcat's server.xml file? That is the meaning expressed by Reloadable).

If you want to write additional servlets, you may need to modify the web.xml file for your web application. If this is, you will need to bounce (Bounce, which is also restarted) the server so that the modifications made will take effect.

to sum up

This article shows how to complete the end-to-end Java development environment. The first part demonstrates the establishment and use of the MIDlet development environment. This part of the tutorial (that is, second part) shows how to configure and use the servlet development environment. In this part, you have learned how to install and run a server, and how to write and publish servlets. Then, you have connected the MIDlet world and the servlet world, create a simple end-to-end Java solution.

As the starting point of the world's other parts, servlet indicates the road to all the power of J2SE and J2EE. This is the way to create a strong end-to-end Java application. MIDP is relatively small, but by dialogue with servlet, they can do a lot of work.

For more information on the design of more end-to-end Java applications, please refer to the White Paper Wireless Blueprints (wireless blueprint). It provides example applications created using end-to-end Java technology.

转载请注明原文地址:https://www.9cbs.com/read-57554.html

New Post(0)