J2ME用戶登錄驗證
[說明]
J2ME用戶登錄驗證,一直沒有搞定怎么回事,網(wǎng)上搜到 [J2ME/J2EE實現(xiàn)用戶登錄交互] ,還是不能運行,問題主要出在Servlet上,沒有看過,不會配置,很是郁悶,前天在同學(xué)SpringChen的指點下,學(xué)會了配置,今天終于搞懂了J2ME用戶登錄驗證機制,非常高興,隨把調(diào)試的程序貼出來,以備以后查閱。
代碼中,修改了原程序不合理及條例不清楚的部分,故升級為2.0版本,特此聲明。
[代碼部分]
實現(xiàn)功能:
用手機客戶端進行登錄服務(wù)器,然后服務(wù)器返回消息進行交互。
服務(wù)器代碼:
需要配置Servlet,首先熟悉Servlet相關(guān)知識。
LoginServlet:
package packageOne;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/** *//**
* 服務(wù)器端代碼, 需配置Servlet.
* Time: 2008 09 03 .
*/
public class LoginServlet extends HttpServlet


{
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException

{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException

{
// 得到客戶端傳入的數(shù)據(jù)(用戶名和密碼)
String username = request.getParameter("username");
String password = request.getParameter("password");
// 構(gòu)建輸出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
// 邏輯操作(這里寫你的邏輯判斷)
if (username.equals("dcf") && password.equals("admin"))

{
// 響應(yīng)數(shù)據(jù)
dos.writeUTF("true");
} else

{
// 響應(yīng)數(shù)據(jù)
dos.writeUTF("false");
}
//獲得寫入的字節(jié)數(shù)組流
byte[] data = baos.toByteArray();
// 設(shè)置服務(wù)器響應(yīng)參數(shù)
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLength(data.length);
response.setContentType("application/octet-stream");
// 構(gòu)建輸出流, 寫入要返回給客戶端的數(shù)據(jù)
OutputStream os = response.getOutputStream();
os.write(data);
os.close();
}

}

手機客戶端代碼:
LoginForm:
package com;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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;


/** *//**
* 用Http Post方式與服務(wù)器交互
* 修改了轉(zhuǎn)貼源代碼中不合理的部分
* @author Du Changfeng 2008 09 03
* @version 2.0
*/
public class LoginForm extends MIDlet implements CommandListener


{
private Form form = null;
private Display display = Display.getDisplay(this);;
private Command login = null;
private Command exit = null;
private TextField username = null;
private TextField password = null;
private Alert alert = null;
private Alert error = null;

public LoginForm()

{
form = new Form("用戶登錄");
display.setCurrent(form);
login = new Command("登錄", Command.SCREEN, 1);
exit = new Command("退出", Command.EXIT, 1);
form.addCommand(login);
form.addCommand(exit);

username = new TextField("用戶名", "", 20, TextField.ANY);
password = new TextField("密 碼", "", 20, TextField.PASSWORD);

form.append(username);
form.append(password);
form.setCommandListener(this);
}

public void initAlertOK()

{
alert = new Alert("提示", "登錄成功 !\r\n您的用戶名為:" + username.getString()
+ "\r\n密碼為:" + password.getString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}

public void initAlertError()

{
error = new Alert("提示", "登錄失敗,用戶名或密碼錯誤", null, AlertType.ERROR);
display.setCurrent(error);
}

protected void startApp() throws MIDletStateChangeException

{

}


/** *//**
* 事件處理
*/
public void commandAction(Command cmd, Displayable dis)

{
// 點擊退出按鈕事件
if (cmd.getCommandType() == Command.EXIT)

{
System.out.println("exit");
this.notifyDestroyed();
}
if (cmd == login)

{
// 必須開啟獨立線程來處理Http請求,否則會造成死鎖
new Thread(new Runnable()

{
public void run()

{
try

{
inTurnServer();
} catch (Exception e)

{
e.printStackTrace();
}
}
}).start();

}
}


/** *//***********************************************
* 用Post與服務(wù)器交互相關(guān)代碼
*/
public void inTurnServer()

{
// 服務(wù)器請求地址
String url = "http://localhost:80/testLogin/login";
// 用戶輸入的用戶名
String username = this.username.getString();
// 用戶輸入的密碼
String password = this.password.getString();
// 要發(fā)送的數(shù)據(jù)
String formData = "username=" + username + "&password=" + password;
// 轉(zhuǎn)換顯字節(jié)流
byte[] data = formData.getBytes();

try
{
// 用url建立一個Http連接(安全的)
HttpConnection conn = (HttpConnection) Connector.open(url);

/** *//****以下為 設(shè)置連接屬性****/
// 設(shè)置請求類型為POST
conn.setRequestMethod(HttpConnection.POST);
// 設(shè)置一般的請求屬性
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Configuration/CLDC-1.0");
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.setRequestProperty("Connection", "close");
// 設(shè)置寫入流的長度
conn.setRequestProperty("Content-Length", Integer
.toString(data.length));

// 新建輸出流,對數(shù)據(jù)流進行操作
OutputStream os = conn.openOutputStream();
// 寫入要Post的數(shù)據(jù)
os.write(data);
os.close();
// 得到Http響應(yīng)代碼
int rc = conn.getResponseCode();
if (rc == HttpConnection.HTTP_OK)

{
// 構(gòu)建輸入流
DataInputStream dism = new DataInputStream(conn
.openInputStream());
// 讀取服務(wù)器返回的字節(jié)流
String result = dism.readUTF();
dism.close();
// 判斷
if (result.equals("true"))

{
// 顯示登錄成功
this.initAlertOK();
}
if (result.equals("false"))

{
// 顯示登錄失敗
this.initAlertError();
// 將輸入框置空
this.username.delete(0, this.username.getString().length());
this.password.delete(0, this.password.getString().length());
}
}
} catch (IOException e)

{
e.printStackTrace();
System.out.println("聯(lián)網(wǎng)出錯。");
//如果請求路徑不正確,或?qū)傩栽O(shè)置錯誤,或服務(wù)器端的問題導(dǎo)致無法正確聯(lián)網(wǎng)
error = new Alert("提示", "聯(lián)網(wǎng)出錯", null, AlertType.ERROR);
display.setCurrent(error);
}
}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException

{

}

protected void pauseApp()

{

}

}

附一:服務(wù)器端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">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>packageOne.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
附二:服務(wù)器端index.jsp配置(可選內(nèi)容)
<FORM action="<%=request.getContextPath()%>/login" method="post" name="99">
<input type="text" name="username" />
<input type="text" name="password" />
<INPUT type="submit" name="toLogin" value="登錄">
</FORM>
<End>