Build your mail program Jacky Pan on the J2ME platform
Table of contents
1. Introduction to the tutorial and the installation of the program 2. Structure of the program 3. Design of the interface 4. Management 5. MIDLET and Servlet network connection 6. Servlet and JavaMail 7. Simple XML 8. Summary 1. Introduction to the tutorial And the installation of the program
This tutorial tells how to write a simple email application on the J2ME platform, including interface design, email / accept / modification / deletion of the mail account, and writing in the background servlet.
In order to run the demo program belled in this tutorial, you need to install the following software: 1. WTK2.0 (java.sun.com) 2. Apache Tomcat (www.apache.org)
Steps to install and run sample programs: 1. Download MicroMail Beta.zip from http://groups.yahoo.com/group/oritec/files/ (including source code and binary files) 2. Unzip MicroMail Beta.zip to $ TMP 3. Create a new directory in $ 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 the address of the URL for Mailagent http: // server / mail / mailagent
2. Structure of the program
The Client-Web Server-Mail Server three-layer architecture is used, as shown in Figure 1.
MIDLET
Cell Phone
Servlet
(Web Server)
Mail Server
My Application
Figure 1
Cell Phone passes the request (Accept / Send Mail) to Web Server, and the Web Server converts these HTTP requests to requests for POP3 or SMTP Server. POP3 / SMTP Server performs the corresponding request and returns the corresponding to Cell Phone via Web Server.
The client (PDA / mobile phone) is a program on the J2ME platform. MIDP2 provides some basic network connection APIs. With these APIs, the J2ME program can make HTTP requests to the far end and accept the response to deliver the data stream.
MAILAGENT is servlet to receive requests from the client, and call the Java Mail API to convert these requests into requests for remote Mail Server while passing the Mail Server response to the client.
So why should I use this architecture? This is because MIDP2.0 only supports HTTP protocols without supporting other application layer protocols such as POP3 and SMTP, while J2EE provides a complete Java Mail's API, so consider converting HTTP requests into POP3 or SMTP requests via a servlet. Another reason is that many operators may only provide limited network access capabilities, and the flexibility of program deployment is provided through an Agent.
The following is a brief introduction to the structure of the source code. In the user interface of the client, the class definition program in the UI package, the class in the utility package defines the operation of the database, the network connection, XML resolution, etc., the class in the mail package is defined. Mail account, head of the message. Ui package:
Accountform.javaaccountslist.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
The server side has only one file mailagent.java, which contains a servlet to make the bridge of MIDlet and mail servers.
3. Design of interface
MIDP 2.0 provides a large number of API for developers to create and control user interfaces. The Screen components such as List, Form, TextBox, Alert, etc. are available in the package javax.microedition.lcdui, which can include a series of Items, such as ChoiceGroup, TextField, StringItem, etc. in the Form. A Command component is also provided, as well as the corresponding Listener.
Source File Ui / Mailmidlet.java Defines the entry of the program and the main page of MicroMail. As the main page is a list, several functional modules are displayed, including adding an account, modifying / deleting an account, accepting a message, and sending an email.
Figure 2
Public mailmidlet () {Display = display.getdisplay (this); / * Create a 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 * / mainlist.addcommand for Mainlist (CMOK ); Mainlist.addcommand (cmexit); / * mailmidlet implements the CommandListener interface, can be used as a listener * / mainlist.setcommandlistener (this); ......}
With Accountform (Source File Ui / Accountform.java), users can add and modify the mail account, as shown in Figure 3.
Figure 3a figure 3b
Accountform contains 6 TextField, which displays 6 attributes of the mail account, respectively. Account is the name of the account and the unique identifier of the account, and cannot be rewarded. Address is the address of the message, such as Bill@ms.com. User, Password is the username and password registered in the mail service provider. POP3, SMTP is the name or address of the POP3 server and the SMTP server. Private void setContent (Mailaccount Macc) {Account = New Textfield ("Account:", ", 20, TextField.Any); address = new textfield (" Address; ",", 40, Textfield.emailAddr); user = New TextField ("User Name:", ", 20, TextField.Any); Password = New Textfield (" Password: ",", 20, TextField.Password); POP3 = New TextField ("POP3 Server:", "", 20, textfield.any; SMTP = New TextField ("SMTP Server:", ", 20, TextField.Any); if (Macc! = NULL) {Account.setstring (macc.accountname); address. SetString (macc.address); user.setstring (macc.username); password.setstring; pop3.setstring (macc.pop3server); SMTP.STSTRING (Macc.smtpserver);}
append (account); append (address); append (user); append (password); append (pop3); append (SMTP);
} Other pages are similar to AccountForm, and details are not described herein, please refer to the source code and the MIDP API document. 4. Management of accounts
The creation, modification, and deletion of the mail account involves access to the data record. MIDP provides a mechanism called record management system to store and access data.
Javax.microEdition.rms.RecordStore provides some API to operate this system. The 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 the RecordStore object, respectively.
These methods are encapsulated in Utility / Dboperator.java to achieve addition, modification, and delete the operation of the mail account. Take an account as an example, the following addRecord method is used to add a record to the RecordStore, and add the mail account represented by this record to an Accounts, and Accounts is a VECOTR to store the current account in the system. The parameter STR contains all the information of the account, such as account name, address, username, password, POP3, SMTP, etc., which are separated from spaces. 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);
/ * Accounts while the account is added to the vector * / MailAccount mailacc = MailAccount.createMailAccountFromString (id, str); accounts.addElement (mailacc);} catch (RecordStoreException rse) {rse.printStackTrace ();}
} 5. MIDLET and Servlet network connection
The MIDP network API is defined in the package javax.microedition.io, where HTTPConnection provides support for the HTTP protocol.
In the file uTility / NetWorker.java, you will receive the message list set measure, accept the contents of a message, and send mail SendMessage and so on. Take SendMessage as an example.
Public string url, final string formdata // send a message {/ * Create a new process * / thread t = new thread () {public void run () {httpConnection http = NULL;
Byte [] data = formdata.getbytes (); try {/ * opens and returns an HTTP connection * / http = (httpConnection) Connector.Open (URL); ...... / * Set HTTP request head * / http .setRequestMethod (HttpConnection.POST); http.setRequestProperty ( "Content-Type", "application / x-www-form-urlencoded"); http.setRequestProperty ( "User-Agent", "Profile / MIDP-1.0 Configuration / CLDC -1.0 "); http.setRequestProperty (" Content-Language "," EN-US); http.setRequestProperty ("Accept", "Application / Oct-stream"); http.setRequestProperty ("Connection", "Close" ); // Optional http.setRequestProperty ("content-length", integer.tostring (data.length)); ... / * Open output stream * /
Outputstream Os = http.openoutputstream ();
/ * Write mail data * /
Os.write (data);
/ * Close output stream * /
Os.close ();} catch (ooException ooe) {...} finally {try {/ * closes the connection * / if (http! = null) http.close ();} catch (ooException ignored) { }}}}; / * Startup process * / T.Start ();
}
The MIDLET issues a request for accepting or sends a message to the server through the HTTP connection, and servlet issues a corresponding request to the mail server according to different requests and passes the return result to the MIDlet. 6. Servlet and JavaMail
The J2EE provides support for mail-related protocols, package javax.mail and package Javax.mail.Interne defined JavaMail APIs. Below is the code snippet for servlet processing receiving mailing list in Mailagent.java. public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter out = response.getWriter (); String typeStr = request.getParameter ( "type"); int type = Integer.parseInt (typeStr);
String pop3Server; String username; String password; Properties props; String provider; switch (type) {case RECEIVE_LIST: / * parameter extraction pop3 server, user name, password * / pop3Server = request.getParameter (paramPOP3); username = request.getParameter (paramname); password = request.getParameter (parampass); if (pop3server == null || username == null || Password == null) {out.print (status_bad); // xml? Return;} = new Properties (); provider = "POP3"; try {/ * Connect POP3 Server at the specified username and password * / session session = session.getDefaultInstance (Props, NULL); ST Ore store.getStore (Provider); Store.connect (POP3Server, Username, Password); / * Get inbox inbox * / folder inbox = store.getfolder ("inbox"); if (Inbox == null) { Out.print (status_bad); // Xml? Return;} / * Open the inbox * / inbox.open (Folder.Read_only); / * Get the list of mail in your inbox,
And write * / writeXML (Inbox.getMess (), out); Inbox.close (); store.close ();} catch (exception e) {outputln (E.getMessage ()); E .printStackTrace ();} out.close (); break; case rescious_message: ... breaf; case send_message: ... breaf;}} J2EE program compiler, compile and deployment, please refer to the relevant book Or documentation. Http://www.tusc.com.au/tutorial/html/ << Tutorial for building J2ee Applications Using JBoss and Eclipse >> is a good document. 7. Simple XML When you accept emails in MIDlet, you first request a list of current messages in the mailbox. The header information of the message includes the header information of the message, including the sender's address, the subject of the message, the time of transmission, etc., as shown in Figure 4.
Figure 4 may include any characters in the mail topic, so there is no way to separate this information with a particular character, while XML is appropriate for transmitting this information with specific formats. In the servlet side, useful mail header information as an element of XML to the output stream. Private Void Writexml (Message [) {Out.Println ("
In the MIDLET side, the XML is resolved, there are many free XML Parser on the J2ME platform, and KXML is one of them. You can download the source code, JAR file, and API documentation of KXML 1.21 from http://kxml.enhydra.org/. The following is a utility / HeadParser.java processing XML code fragment 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 * / parser.read (XML.Start_Tag, Null, "Mail");
Boolean Trucking = true; boolean first = true;
While (TRUCKING) {/ * reads the next Event * / PE = PARSER.READ ();
IF (pe.gettype () == xml.start_tag) {/ * gets the name of Event * / String name = pe.getname ();
IF ("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 = paser.read (); / * Get Event's content * / subject = pe.getText ();} else f (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 ());}} / * put the message header to the listener processing * / headListener.Itemparsed From, Subject, D ATE, INDEX);} else // Non Message Block {While ((pe.gettype ()! = xml.end_tag) || (pe.getname (). Equals (name) == false) PE = PARSER.READ ();}} F (pe.gettype () == xml.end_tag && pe.getname (). Equals ("mail")) {TRUCKING = false;
}
For details, please refer to the KXML document. JSR172 (J2ME Web Services Specification) proposes to process XML specification on the J2ME platform, interested friends can take a look at the JCP website (http://www.jcp.org), but there may be no vendors or organizations at present Realization. 8. Small junction This paper introduces the writing of the mail program on the J2ME platform, and the knowledge points involved are: 1. J2ME UI 2. Record Store 3. J2ME's network connection / J2ME and J2EE pass 4. Parsing XML IN J2ME 5. 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 J2ee Applications Using jboss and eclipse, http://www.tusc.com.au/tutorial/html/
Author Blog:
http://blog.9cbs.net/rostone/