程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> J2ME >> J2ME/J2EE實現用戶登錄交互

J2ME/J2EE實現用戶登錄交互

編輯:J2ME
實現功能:

  用手機客戶端進行登錄服務器,然後返回消息進行交互.

  服務器代碼:

LoginServlet:
package com;
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;
/** *//*******************************************************************************
*
* @author zdw
*
*/
@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    this.doPost(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    // 得到客戶端傳入的數據(用戶名和密碼)
    String username = request.getParameter("username");
    String password = request.getParameter("passWord");
    // 構建輸出流
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream DOS = new DataOutputStream(baos);
    // 邏輯操作(這裡寫你的邏輯判斷)
    if ("zdw".equals(username) && "admin".equals(passWord))
    {
      // 響應數據
      DOS.writeUTF("true");
    } else
    {
      // 響應數據
      DOS.writeUTF("false");
    }
    //
    byte[] data = baos.toByteArray();
    // 設置服務器響應參數
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentLength(data.length);
    response.setContentType("application/octet-stream");
    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方式與服務器交互
*
* @author zdw
*
*/
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("提示", "登錄成功!!rn您的用戶名為:" + username.getString()
        + "rn密碼為:" + 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();
    }
  }
  /** *//***************************************************************************
   * 與服務器交互相關代碼
   */
  public void inTurnServer()
  {
    try
    {
      // 服務器請求地址
      String url = "http://localhost:8888/LoginWeb/LoginServlet";
      // 用戶輸入的用戶名
      String username = this.username.getString();
      // 用戶輸入的密碼
      String password = this.passWord.getString();
      // 用url建立一個Http連接(安全的)
      HttpConnection conn = (HttpConnection) Connector.open(url);
      // 設置請求類型為POST
      conn.setRequestMethod(HttpConnection.POST);
      // 設置一般的請求屬性
      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");
      // 要發送的數據
      String formData = "username=" + username + "&password=" + passWord;
      // 轉換顯字節流
      byte[] data = formData.getBytes();
      // 設置寫入流的長度
      conn.setRequestProperty("Content-Length", Integer
          .toString(data.length));
      OutputStream os = conn.openOutputStream();
      os.write(data);
      os.close();
      // 得到Http響應代碼
      int rc = conn.getResponseCode();
      // 正常響應
      if (rc == HttpConnection.HTTP_OK)
      {
        // 構建輸入流
        DataInputStream dism = new DataInputStream(conn
            .openInputStream());
        // 讀取服務器返回的字節流
        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();
    }
  }
  protected void destroyApp(boolean arg0) throws MIDletStateChangeException
  {
  }
  protected void pauseApp()
  {
  }
}

  注意此工程為MyEclipse工程,您需要安裝wtk和tomcat才能正常運行此程序.

  登錄圖:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved