Program to build your mail program on the J2ME platform
Jacky Pan
Table of Contents
1. Introduction to tutorials and installation of procedures
2. Structure of the procedure
3. The design of the interface
4. Management of Accounts
5. Network connection to MIDlet and servlet
6. servlet and JavaMail
7. Simple XML
8. Summary
1. Introduction to tutorials and installation of procedures
This tutorial describes how to write a Simple mail application on the J2ME platform, including the design of the interface, the sending/receiving of mails, the creation/modification/deletion of mail accounts, and the writing of the background servlet.
To run the demo program that is shown in this tutorial, you need to install the following software:
1. WTK2.0 (java.sun.com)
2. Apache Tomcat (www.apache.org)
To install and run the sample program:
1. Download Micromail beta.zip from http://groups.yahoo.com/group/OriTec/files/(including source code and binaries)
2. Extract Micromail Beta.zip to $tmp
3. Build a new catalogue under $wtk/apps Micromail
4. Copy $tmp/src/client/* to $WTK/apps/micromail/src/
5. Copy $/tmp/bin/server/mail.war to $tomcat/webapps/
6. Run Tomcat
7. Run WTK2.0, "Open Project" and select Micromail
8. Set URL to mailagent address http://server/mail/MailAgent
2. Structure of the procedure
Adopt the Client-web Server-mail Server three-tier architecture, as shown in Figure 1.
MIDlet
(Cell Phone)
Servlet
(Web Server)
Mail Server
My application
Figure 1
Cell Phone passes requests (Accept/Send mail) to the Web Server,web server to convert these HTTP requests to requests for POP3 or SMTP server. The POP3/SMTP server executes the appropriate request and returns it to cell Phone via the Web server.
The client (pda/mobile phone) is a program on the J2ME platform. MIDP2 provides some basic network connectivity APIs. These APIs allow the J2ME program to send HTTP requests to the remote and accept the response to pass the data stream.
Mailagent is a servlet used to receive requests from clients and invoke the Java Mail API to turn these requests into requests for Remote mail server and to pass mail server responses to clients.
So why do you use such a framework? This is because MIDP2.0 only supports the HTTP protocol and does not support other application-layer protocols such as POP3 and SMTP, and Java-EE provides the full set of the JavaScript API, so consider converting HTTP requests into POP3 or SMTP requests through a servlet. Another reason is that many operators may only provide limited access to the network, and the flexibility of program deployment is provided through an agent.
The following briefly introduces the structure of the source code, in the client, the UI package class defines the user interface of the program, the class in the utility package defines the operation of the database, the connection of the network, the parsing of the XML, etc.
UI Package:
Accountform.java
Accountslist.java
Confirm.java
Confirmlistener.java
Mailmidlet.java
Messagelist.java
Progressform.java
Sendmessage.java
Writecontent.java
Utility Package:
Dboperator.java
Headparser.java
Netadapter.java
Networker.java
Parserlistener.java
Mail package:
Mailaccount.java
Messagehead.java
Server-side only one file Mailagent.java, contains a servlet, used to do midlet and mail server bridge.
3. The design of the interface
MIDP2.0 provides a wide range of APIs for developers to create and control user interfaces. The list, form, TextBox, alert, and screen components are available in the package Javax.microedition.lcdui, which can contain a series of item, such as Choicegroup, TextField, Stringitem and so on. The command component is also available in the package, along with the corresponding listener.
The source file Ui/mailmidlet.java defines the entry for the program and the main page of the Micromail. As shown in Figure 2, the home page is a list that shows several functional modules, including adding accounts, modifying/deleting accounts, accepting emails, and sending emails.
Figure 2
Public Mailmidlet ()
{
display = Display.getdisplay (this);
/* Create List */
Mainlist = new List ("MicroMail0.1", choice.implicit);
/* Create two control buttons OK and exit * *
Cmok = new Command ("OK", Command.ok, 1);
Cmexit = new Command ("Exit", Command.exit, 1);
* * Add content to mainlist.
Mainlist.append ("ADD account", NULL);
Mainlist.append ("Edit account", NULL);
Mainlist.append ("Receive message", NULL);
Mainlist.append ("Send message", NULL);
/* Add command for mainlist/*
Mainlist.addcommand (Cmok);
Mainlist.addcommand (Cmexit);
/* Mailmidlet implements the Commandlistener interface, can be used as a listener/
Mainlist.setcommandlistener (this);
......
}
Through Accountform (source file Ui/accountform.java), users can add and modify mail accounts, as shown in Figure 3.
Figure 3a Figure 3b
The Accountform contains 6 TextField, showing the 6 properties of the mail account, respectively. Account name and account is the only identification, not duplicate. Address is a message, such as bill@ms.com. User, password is the username and password registered with the mail service provider. POP3, SMTP is the name or address of the POP3 server and SMTP server.
private void SetContent (Mailaccount Macc)
{
account = new TextField ("Account:", "", Textfield.any);
Address = new TextField ("address;", "", textfield.emailaddr);
user = new TextField ("User Name:", "", Textfield.any);
Password = new TextField ("Password:", "", Textfield.password);
POP3 = new TextField ("POP3 Server:", "", Textfield.any);
SMTP = new TextField ("SMTP Server:", "", Textfield.any);
if (Macc!= null)
{
Account.setstring (Macc.accountname);
Address.setstring (macc.address);
User.setstring (Macc.username);
Password.setstring (Macc.password);
Pop3.setstring (MACC. Pop3server);
Smtp.setstring (MACC. SmtpServer);
}
Append (account);
Append (address);
Append (user);
Append (password);
Append (POP3);
Append (SMTP);
}
Other pages are similar to Accountform, and don't repeat them here, please refer to the source code and the MIDP API documentation.
4. Management of Accounts
The creation, modification, and deletion of mail accounts involve access to data records. MIDP provides a mechanism called the record Management system to store and access data.
Javax.microedition.rms.RecordStore provides some APIs to manipulate the system. Static method Openrecordstore is used to open or create a RecordStore object. Methods AddRecord, Getrecord, DeleteRecord, Setrecord are used to add, access, delete, or modify records in RecordStore objects, respectively.
These methods are encapsulated in Utility/dboperator.java to enable adding, modifying, and deleting mail accounts. As an example of adding an account, the following AddRecord method is used to add a record to the recordstore while adding the mail account represented by this record to a accounts, accounts is a VECOTR to store the current account in the system. Parameter str contains all the information about the account, such as account name, address, username, password, POP3,SMTP, etc., separated by a space.
public void AddRecord (String str)
{
int id;
byte[] rec = str.getbytes ();
String record = str;
Try
{
/* Add a record to the recordstore * *
id = Rs.addrecord (rec, 0, rec.length);
/* Add the account to the accounts vector at the same time * *
The MIDP network API is defined in the package Javax.microedition.io, where httpconnection provides support for the HTTP protocol.
These network APIs are implemented in file Utility/networker.java to receive the setmessagelist of the mailing list in the current mailbox, to accept the contents of a message receivemessage, to send mail SendMessage, and other functions. Take SendMessage as an example.
public void SendMessage (final string url, final string formData)//send a message
MIDlet sends a request to Servelet to accept or send a message over an HTTP connection, the servlet sends the corresponding request to the mail server based on a different request and passes the return result to MIDlet.
6. servlet and JavaMail
Java EE provides support for mail-related protocols, and JavaMail APIs are defined in package Javax.mail and package javax.mail.internet. The following is a snippet of code in the Mailagent.java in which the servlet handles the request for a mailing list.
public void DoPost (HttpServletRequest request, httpservletresponse response)
/* Get the mailing list in the Inbox and write it in XML * *
WriteXml (Inbox.getmessages (), out);
Inbox.close (FALSE);
Store.close ();
}
catch (Exception e)
{
Out.println (E.getmessage ());
E.printstacktrace ();
}
Out.close ();
Break
Case Receive_message:
......
Break
Case Send_message:
......
Break
}
}
Java-EE program compilation and deployment please refer to the relevant books or documents. http://www.tusc.com.au/tutorial/html/<<tutorial for building Java EE applications using JBOSS and eclipse>> It's a nice piece of documentation.
7. Simple XML
When MIDlet accepts a message, it first requests the servlet to send a list of the current messages in the mailbox. The list includes the header information for the message, including the sender's address, the subject of the message, the time it was sent, and so on, as shown in Figure 4.
Figure 4
There may be any character in the subject of the message, so there is no way to separate the information with a particular character, and XML is just right for the transmission of this information in a particular format. On the servlet side, the useful message header information is written to the output stream as an element of XML.
To parse this XML at the MIDlet end, there are a lot of free XML parser,kxml on the J2ME platform. You can download the source code, jar files, and API documentation for Kxml 1.21 from http://kxml.enhydra.org/.
The following is a snippet of code that processes XML in Utility/headparser.java
public void Parse (InputStream in) throws IOException
{
Reader reader = new InputStreamReader (in);
Xmlparser parser = new Xmlparser (reader);
Parseevent PE = NULL;
Parser.skip ();
/* Read a name for Mail's event * *
Parser.read (Xml.start_tag, NULL, "Mail");
Boolean trucking = true;
Boolean-i = true;
while (trucking)
{
/* Read the next event * *
PE = Parser.read ();
if (pe.gettype () = = Xml.start_tag)
{
* * Get the name of the event
String name = Pe.getname ();
if (name.equals ("message"))
{
String from = null;
String subject = NULL;
String date = null;
int index =-1;
while ((Pe.gettype ()!= Xml.end_tag) | |
(Pe.getname (). Equals (name) = = False))
{
PE = Parser.read ();
if (pe.gettype () = = Xml.start_tag &&
Pe.getname (). Equals ("subject"))
{
PE = Parser.read ();
/* Get the contents of the event * *
Subject = Pe.gettext ();
}
else if (pe.gettype () = = Xml.start_tag &&
Pe.getname (). Equals ("from"))
{
PE = Parser.read ();
From = Pe.gettext ();
}
else if (pe.gettype () = = Xml.start_tag &&
Pe.getname (). Equals ("date"))
{
PE = Parser.read ();
Date = Pe.gettext ();
}
else if (pe.gettype () = = Xml.start_tag &&
Pe.getname (). Equals ("index"))
{
PE = Parser.read ();
index = Integer.parseint (Pe.gettext ());
}
}
/* Send the headers to the listener for processing * *
The use of specific APIs please refer to the Kxml documentation. JSR172 (J2ME Web Services specification) proposes a specification for XML processing on the J2ME platform, and interested friends can take a look at JCP's website (http://www.jcp.org), But there may not be a manufacturer or organization to implement it.
8. Summary
This paper introduces the writing of mail program on J2ME platform, and the knowledge points involved are as follows:
1. J2ME UI
2. Record Store
3. J2ME Network Connections/J2ME and Java EE transfer of data between
4. Parsing XML in J2ME
5. A simple servlet
6. Java Mail APIs
References are:
1. MIDP2.0 Spec, http://www.jcp.org
2. <<core J2me>>, http://www.corej2me.com/
3. <<j2me in Nutshell>>, http://www.oreilly.com
4. Tutorial for building Java EE applications using JBOSS and ECLIPSE, http://www.tusc.com.au/tutorial/html/
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.