Serialization mechanism in J2ME network

xiaoxiao2021-03-06  54

The serialization mechanism is not supported in the CLDC, but this does not affect our use of this effective mechanism in J2ME networking or RMS operations, this article will tell how J2ME networking is performed using serialization mechanisms.

If the reader is not familiar with the use of Tomcat and Java IO, please refer to the following two articles as the preparation of this article. Java's basic data type and stream, Tomcat Getting Started Guide. We want to write a user-registered application, users fill in their own information and send data to the server by the network, and we use servet to receive the user's data. This is the advantage that when we need to modify the user registration option, if we add an option, we do not need to modify the network network, just modify the serialization and reverse sequence method of the user class. Let's take a look at our Account class, which is packaged on the user's registration information and provides two important methods serialize () and deserialize (). Package com.j2medev.mingjava;

Import java.io. *;

Public class account {private string username = ""; private string email = "; private int agent = 0; private bolean gender = false;

Public Account () {

}

Public Account (String Username, String Email, Int Age, Boolean Gender) {this.Username = Username; this.email = email; this.age = age; itute = gender;

Public void serialize (DOS.WRITEUTF (Username); dos.writeint (age); dos.writeboolean (GENDER);

public static Account deserialize (DataInputStream dis) throws IOException {Account account = new Account (); account.userName = dis.readUTF (); account.email = dis.readUTF (); account.age = dis.readInt (); account .gender = dish.readboolean (); Return Accent;

Public string toString () {return "username =" username "email =" email "age =" AGE "gender =" (gender? "Male": "female");}} when networking operation, only need to call account.serialize (dos), e.g. private void connect (String url) {HttpConnection httpConn = null; DataOutputStream dos = null; InputStream is = null; try {System.out.println ( "connecting to server ..... "); httpConn = (HttpConnection) Connector.open (url); httpConn.setRequestMethod (HttpConnection.POST); dos = new DataOutputStream (httpConn.openOutputStream ()); System.out.println (account. Tostring ()); Account.Serialize (DOS); dos.close ();} catch (ioexception e) {E.PrintStackTrace ();}} The server is concluded after the client passed the stream, it is simpler, Calling Account.deSerialize (DIS) You can get an Account object. protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int length = request.getContentLength (); System.out.println (length); DataInputStream dis = new DataInputStream (request.getInputStream ()); Account myAccount = Account . deeserialize (dish); system.out.println (myaccount.tostring ());

Let's do a simple MIDlet below to collect the registration information filled in the user and then send it to the server. The interface is as follows:

The code is as follows: package com.j2medev.mingjava;

import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.ChoiceGroup; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition. lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.TextField; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import java.io *;. import javax. Microedition.io. *; public class networkmidlet extends midlet imports commandlistener {

Private Display Display; Private textfield UserName; Private textfield Email; Private ChoiceGROUP GENDER; Private NetWorkthread NT;

Public Static Final Command ConnectCommand = New Command ("Connect", Command.Item, 2); Public Static Final Command EXITCOMMAND = New Command ("EXIT", Command.exit, 1); Public Static Final String URL = "http: / / localhost: 8088 / net / myservlet ";

Protected void Startapp () throws midletStateChangeException {initmidlet ();

} Private void initmidlet () {Display = display.getdisplay (this); mainform = new form ("personal information"); username = new textfield ("Name", NULL, 20, TextField.Any); email = new textfield "Electronic Mail", NULL, 25, TextField.emailaddr; age = new textfield ("age", null, 20, textfield.any; gender = new choicegroup; gender.append ( "Men", NULL; Gender.Append ("Female", NULL); MainForm.Append (Email); Mainform.Append (age); mainform.append (gender); mainform.addcommand connectCommand); mainForm.addCommand (exitCommand); mainForm.setCommandListener (this); display.setCurrent (mainForm); nt = new NetworkThread (this); nt.start ();} private void exitMIDlet () {try {destroyApp (false NotifyDestroyed ();} catch (MIDletStateChangeexception E) {E.PrintStackTrace ();}}

protected void pauseapp () {}

Protected Void DestroyApp (Boolean Arg0) throws MidletStateChangeException {}

public void commandAction (Command arg0, Displayable arg1) {if (arg0 == connectCommand) {String name = userName.getString (); String mail = email.getString (); int myAge = Integer.parseInt (age.getString ()) INT i = gender.getSelectedIndex (); boolean mygender = i == 0? True: false; Account Account = New Account (name, mail, myage, mygender); nt.setAccount (account); // system.out. Print.toString ()); synchronized (this) {notify ();}}} else if (arg0 == exitcommand) {exitmidlet ();}}

Class networkthread extends thread {private networkmidlet midlet; private bolean going = true; private account account = null;

Public NetworkThread (Networkmidlet MIDlet) {this.midlet = MIDlet;

Public synchronized void setaccount (account) {this.account = account;}

Public void Run () {while {synchronized (midlet) {type {midlet.wait ();} catch (interruptedException e) {E.PrintStackTrace ();}} connect (URL);

}

private void connect (String url) {HttpConnection httpConn = null; DataOutputStream dos = null; InputStream is = null; try {System.out.println ( "connecting to server ....."); httpConn = (HttpConnection) Connector. open (url); httpConn.setRequestMethod (HttpConnection.POST); dos = new DataOutputStream (httpConn.openOutputStream ()); System.out.println (account.toString ()); account.serialize (dos); dos.close ( );} catch (ioException e) {E.PrintStackTrace ();}}}

}

We only print to the console after servement of data from the client. The code of the servlet is as follows: import java.io.DataInputStream; import java.io ioException;

Import javax.servlet.ServletException; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse;

Public class myservlet extends httpservlet {

Protected void doget (httpservletRequest Request, httpservletResponse response) throws servletexception, ioException {dopost (request, response);}

protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int length = request.getContentLength (); System.out.println (length); DataInputStream dis = new DataInputStream (request.getInputStream ()); Account myAccount = Account . deeserialize (DIS); system.out.println (MyAccount.tostring ());}} Be sure to put the Account class into the Server side, so it can achieve reverse selecente. (Note that Client and Server Package are not necessarily). Start Tomcat servers, we can see it on the server when the client sends data to the server.

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

New Post(0)